def _findLine(self, ws): """Return a peak position workspace.""" # TODO There should be a better algorithm in Mantid to achieve this. integratedWSName = self._names.withSuffix('integrated') integratedWS = Integration(InputWorkspace=ws, OutputWorkspace=integratedWSName, EnableLogging=self._subalgLogging) transposedWSName = self._names.withSuffix('transposed') transposedWS = Transpose(InputWorkspace=integratedWS, OutputWorkspace=transposedWSName, EnableLogging=self._subalgLogging) self._cleanup.cleanup(integratedWS) # Convert spectrum numbers to WS indices. wsIndices = numpy.arange(0, ws.getNumberHistograms()) xs = transposedWS.dataX(0) ys = transposedWS.readY(0) numpy.copyto(xs, wsIndices) indexOfMax = ys.argmax() heightGuess = ys[indexOfMax] posGuess = xs[indexOfMax] sigmaGuess = 3 f = 'name=Gaussian, PeakCentre={}, Height={}, Sigma={}'.format( posGuess, heightGuess, sigmaGuess) fitResult = Fit(Function=f, InputWorkspace=transposedWS, EnableLogging=self._subalgLogging) self._cleanup.cleanup(transposedWS) peakPos = fitResult.Function.PeakCentre posTable = self._createFakePeakPositionTable(peakPos) return posTable
def _findLine(self, ws): """Return a peak position workspace.""" # TODO There should be a better algorithm in Mantid to achieve this. integratedWSName = self._names.withSuffix('integrated') integratedWS = Integration(InputWorkspace=ws, OutputWorkspace=integratedWSName, EnableLogging=self._subalgLogging) transposedWSName = self._names.withSuffix('transposed') transposedWS = Transpose(InputWorkspace=integratedWS, OutputWorkspace=transposedWSName, EnableLogging=self._subalgLogging) self._cleanup.cleanup(integratedWS) # Convert spectrum numbers to WS indices. wsIndices = numpy.arange(0, ws.getNumberHistograms()) xs = transposedWS.dataX(0) ys = transposedWS.readY(0) numpy.copyto(xs, wsIndices) indexOfMax = ys.argmax() heightGuess = ys[indexOfMax] posGuess = xs[indexOfMax] sigmaGuess = 3 f = 'name=Gaussian, PeakCentre={}, Height={}, Sigma={}'.format(posGuess, heightGuess, sigmaGuess) fitResult = Fit(Function=f, InputWorkspace=transposedWS, EnableLogging=self._subalgLogging) self._cleanup.cleanup(transposedWS) peakPos = fitResult.Function.PeakCentre posTable = self._createFakePeakPositionTable(peakPos) return posTable
def test_2d_scanning_workspace(self): input_ws = CreateSampleWorkspace(NumMonitors=0, NumBanks=3, BankPixelWidth=2, XMin=0, XMax=5, BinWidth=1, NumScanPoints=7) calibration_x = np.array([0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]) calibration_y = np.arange(12) calibration_ws = CreateWorkspace(DataX=calibration_x, DataY=calibration_y, Nspec=4) calibrated_ws = ApplyDetectorScanEffCorr(input_ws, calibration_ws) tmp = Transpose(calibration_ws) tmp = tmp.extractY().flatten() to_multiply = np.repeat(tmp, 5 * 7) to_multiply = np.reshape(to_multiply, [7 * 12, 5]) for det in range(7 * 12): for bin in range(5): self.assertEquals( calibrated_ws.readY(det)[bin], input_ws.readY(det)[bin] * to_multiply[det][bin])
def PyExec(self): input_ws = self.getProperty("InputWorkspace").value eff_ws = self.getProperty("DetectorEfficiencyWorkspace").value transposed = Transpose(InputWorkspace=eff_ws, StoreInADS=False) efficiencies = transposed.extractY().flatten() errors = transposed.extractE().flatten() n_hist = input_ws.getNumberHistograms() if n_hist % efficiencies.size != 0: raise ValueError('Number of histograms in input workspace is not a multiple of number of entries in detector efficiency ' 'workspace.') n_time_indexes = n_hist / efficiencies.size to_multiply = CreateWorkspace(DataY=np.repeat(efficiencies, n_time_indexes), DataE=np.repeat(errors, n_time_indexes), DataX=np.zeros(n_hist), NSpec=n_hist, StoreInADS=False) output = Multiply(LHSWorkspace=input_ws, RHSWorkspace=to_multiply, OutputWorkspace=self.getPropertyValue("OutputWorkspace")) # In the output we should mask the detectors where calibration constant is masked det_IDs = '' n_pixels_per_tube = eff_ws.getNumberHistograms() for spectrum in range(n_pixels_per_tube): if eff_ws.hasMaskedBins(spectrum): masked = eff_ws.maskedBinsIndices(spectrum) for bin in masked: det_IDs += str(bin * n_pixels_per_tube + spectrum + 1) + ',' if det_IDs: MaskDetectors(Workspace=output, DetectorList=det_IDs[:-1]) self.setProperty("OutputWorkspace", output)
def PyExec(self): input_ws = self.getProperty("InputWorkspace").value eff_ws = self.getProperty("DetectorEfficiencyWorkspace").value transposed = Transpose(InputWorkspace=eff_ws, StoreInADS=False) efficiencies = transposed.extractY().flatten() errors = transposed.extractE().flatten() n_hist = input_ws.getNumberHistograms() if n_hist % efficiencies.size != 0: raise ValueError( 'Number of histograms in input workspace is not a multiple of number of entries in detector efficiency ' 'workspace.') n_time_indexes = n_hist / efficiencies.size to_multiply = CreateWorkspace(DataY=np.repeat(efficiencies, n_time_indexes), DataE=np.repeat(errors, n_time_indexes), DataX=np.zeros(n_hist), NSpec=n_hist, StoreInADS=False) output = Multiply( LHSWorkspace=input_ws, RHSWorkspace=to_multiply, OutputWorkspace=self.getPropertyValue("OutputWorkspace")) # In the output we should mask the detectors where calibration constant is masked det_IDs = '' n_pixels_per_tube = eff_ws.getNumberHistograms() for spectrum in range(n_pixels_per_tube): if eff_ws.hasMaskedBins(spectrum): masked = eff_ws.maskedBinsIndices(spectrum) for bin in masked: det_IDs += str(bin * n_pixels_per_tube + spectrum + 1) + ',' if det_IDs: MaskDetectors(Workspace=output, DetectorList=det_IDs[:-1]) self.setProperty("OutputWorkspace", output)
def reduceToPowder(ws, OutputWorkspace, norm=None, taget='Theta', XMin=10, XMax=135, NumberBins=2500): # Add scale by monitor ConvertSpectrumAxis(InputWorkspace=ws, Target=taget, OutputWorkspace=OutputWorkspace) Transpose(InputWorkspace=OutputWorkspace, OutputWorkspace=OutputWorkspace) ResampleX(InputWorkspace=OutputWorkspace, OutputWorkspace=OutputWorkspace, XMin=XMin, XMax=XMax, NumberBins=NumberBins) if norm is not None: ConvertSpectrumAxis(InputWorkspace=norm, Target=taget, OutputWorkspace='__norm') Transpose(InputWorkspace='__norm', OutputWorkspace='__norm') ResampleX(InputWorkspace='__norm', OutputWorkspace='__norm', XMin=XMin, XMax=XMax, NumberBins=NumberBins) Divide(LHSWorkspace=OutputWorkspace, RHSWorkspace='__norm', OutputWorkspace=OutputWorkspace) DeleteWorkspace('__norm') return OutputWorkspace
def dynamicsusceptibility(workspace, temperature, outputName=None, zeroEnergyEpsilon=1e-6): """Convert :math:`S(Q,E)` to susceptibility :math:`\chi''(Q,E)`. #. If the X units are not in DeltaE, the workspace is transposed #. The Y data in *workspace* is multiplied by :math:`1 - e^{\Delta E / (kT)}` #. Y data in the bin closest to 0 meV and within -*zeroEnergyEpsilon* < :math:`\Delta E` < *zeroEnergyEpsilon* is set to 0 #. If the input was transposed, transpose the output as well :param workspace: a :math:`S(Q,E)` workspace to convert :type workspace: :class:`mantid.api.MatrixWorkspace` :param temperature: temperature in Kelvin :type temperature: float :param outputName: name of the output workspace. If :class:`None`, the output will be given some generated name. :type outputName: str or None :param zeroEnergyEpsilon: if a bin center is within this value from 0, the bin's value is set to zero. :type zeroEnergyEpsilon: float :returns: a :class:`mantid.api.MatrixWorkspace` containing :math:`\chi''(Q,E)` """ workspace = _normws(workspace) horAxis = workspace.getAxis(0) horUnit = horAxis.getUnit().unitID() doTranspose = horUnit != 'DeltaE' if outputName is None: outputName = 'CHIofQW_{}'.format(str(workspace)) if doTranspose: workspace = Transpose(workspace, OutputWorkspace='__transposed_SofQW_', EnableLogging=False) c = 1e-3 * constants.e / constants.k / temperature outWS = OneMinusExponentialCor(workspace, OutputWorkspace=outputName, C=c, Operation='Multiply', EnableLogging=False) _removesingularity(outWS, zeroEnergyEpsilon) if doTranspose: outWS = Transpose(outWS, OutputWorkspace=outputName, EnableLogging=False) DeleteWorkspace('__transposed_SofQW_', EnableLogging=False) outWS.setYUnit("Dynamic susceptibility") return outWS
def plot_specular_pixel_check(input_workspace: EventWorkspace, flood_workspace: EventWorkspace, ax): flooded_ws = ApplyFloodWorkspace(input_workspace, flood_workspace) integrated = Integration(flooded_ws, RangeLower=9000, RangeUpper=88000, StartWorkspaceIndex=70, EndWorkspaceIndex=95) integrated_transposed = Transpose(integrated) def _1gaussian(x, ampl, cent, sigma): return ampl * (1 / sigma * (np.sqrt(2 * np.pi))) * (np.exp(-((x - cent)**2) / (2 * sigma)**2)) xval = integrated_transposed.readX(0) yval = integrated_transposed.readY(0) popt_gauss, pcov_gauss = optimize.curve_fit(_1gaussian, xval, yval, p0=[56000, 86, 0.8]) perr_gauss = np.sqrt(np.diag(pcov_gauss)) fit_yvals = _1gaussian(xval, *popt_gauss) ax.plot(xval, yval, "rx") ax.plot(xval, fit_yvals, 'k--') ax.axvline(x=86.0, color='b', linestyle='--') ax.set_xlabel("Spectrum") ax.set_ylabel("Counts") max_pos = fit_yvals.argmax() annot_y = fit_yvals[max_pos] annot_x = xval[max_pos] ax.annotate(f"X:{annot_x}, Y:{annot_y}", xy=(annot_x, annot_y), xytext=(annot_x * 1.02, annot_y)) ax.minorticks_on() ax.grid(True, which="both") ax.set_title("Specular pixel") # make interactive plotly figure fig = go.Figure() fig.add_trace( go.Scatter(x=xval, y=yval, name="Data", mode="markers", marker_symbol=4)) fig.add_trace(go.Scatter(x=xval, y=fit_yvals, mode="lines", name="Fit")) fig.add_vline(x=86, line_dash="dash", line_color="blue") fig.update_layout(xaxis_title="Spectrum", yaxis_title="Counts", width=600, title_text="Specular pixel", title_x=0.5) return fig
def PyExec(self): # get parameter values wsString = self.getPropertyValue("InputWorkspace").strip() #internal values wsOutput = "__OutputWorkspace" wsTemp = "__Sort_temp" #get the workspace list wsNames = [] for wsName in wsString.split(","): ws = mtd[wsName.strip()] if type(ws) == WorkspaceGroup: wsNames.extend(ws.getNames()) else: wsNames.append(wsName) if wsOutput in mtd: DeleteWorkspace(Workspace=wsOutput) sortStat = [] for wsName in wsNames: if "qvectors" in wsName: #extract the spectrum ws = mtd[wsName.strip()] for s in range(0, ws.getNumberHistograms()): y_s = ws.readY(s) tuple = (self.GetXValue(y_s), s) sortStat.append(tuple) sortStat.sort() if len(sortStat) == 0: raise RuntimeError("Cannot find file with qvectors, aborting") #sort spectra using norm of q for wsName in wsNames: ws = mtd[wsName.strip()] yUnit = ws.getAxis(1).getUnit().unitID() transposed = False if ws.getNumberHistograms() < len(sortStat): Transpose(InputWorkspace=wsName, OutputWorkspace=wsName) transposed = True for norm, spec in sortStat: ExtractSingleSpectrum(InputWorkspace=wsName, OutputWorkspace=wsTemp, WorkspaceIndex=spec) if wsOutput in mtd: ConjoinWorkspaces(InputWorkspace1=wsOutput,InputWorkspace2=wsTemp,CheckOverlapping=False) if wsTemp in mtd: DeleteWorkspace(Workspace=wsTemp) else: RenameWorkspace(InputWorkspace=wsTemp, OutputWorkspace=wsOutput) #put norm as y value and copy units from input loopIndex = 0 wsOut = mtd[wsOutput] for norm, spec in sortStat: wsOut.getSpectrum(loopIndex).setSpectrumNo(int(norm*1000)) loopIndex = loopIndex + 1 if len(yUnit) > 0: wsOut.getAxis(1).setUnit(yUnit) if transposed: Transpose(InputWorkspace=wsOutput, OutputWorkspace=wsOutput) RenameWorkspace(InputWorkspace=wsOutput, OutputWorkspace=wsName)
def test_calculate_correction(self): correction = SANSWideAngleCorrection(self._sample, self._trans) self.assertTrue(correction.getNumberHistograms()==self._sample.getNumberHistograms()) self.assertTrue(len(correction.readX(0))== len(self._sample.readX(0))) self.assertTrue(len(correction.readY(0))==len(self._sample.readY(0))) lRange = Min(correction) hRange = Max(correction) lRange = Transpose(lRange) hRange = Transpose(hRange) self.assertTrue(97 > hRange.dataY(0).all()) self.assertTrue(1 >= hRange.dataY(0).all())
def test_calculate_correction(self): correction = SANSWideAngleCorrection(self._sample, self._trans) self.assertEqual(correction.getNumberHistograms(), self._sample.getNumberHistograms()) self.assertEqual(len(correction.readX(0)), len(self._sample.readX(0))) self.assertEqual(len(correction.readY(0)), len(self._sample.readY(0))) lRange = Min(correction) hRange = Max(correction) lRange = Transpose(lRange) hRange = Transpose(hRange) self.assertGreater(97, hRange.dataY(0).all()) self.assertGreaterEqual(1, hRange.dataY(0).all())
def load_data_from_bin(bin_file_name): """ """ ws_name = os.path.basename(bin_file_name).split('.')[0] LoadSpiceXML2DDet(Filename=bin_file_name, OutputWorkspace=ws_name, LoadInstrument=False) # get vector of counts counts_ws = Transpose(InputWorkspace=ws_name, OutputWorkspace='temp') count_vec = counts_ws.readY(0) return ws_name, count_vec
def PyExec(self): input_ws = self.getProperty("InputWorkspace").value eff_ws = self.getProperty("DetectorEfficiencyWorkspace").value transposed = Transpose(InputWorkspace=eff_ws, StoreInADS=False) efficiencies = transposed.extractY().flatten() errors = transposed.extractE().flatten() n_hist = input_ws.getNumberHistograms() if n_hist % efficiencies.size != 0: raise ValueError('Number of histograms in input workspace is not a multiple of number of entries in detector efficiency ' 'workspace.') n_time_indexes = n_hist / efficiencies.size to_multiply = CreateWorkspace(DataY=np.repeat(efficiencies, n_time_indexes),DataE=np.repeat(errors, n_time_indexes), DataX=np.zeros(n_hist), NSpec=n_hist, StoreInADS=False) output = Multiply(LHSWorkspace=input_ws, RHSWorkspace=to_multiply, OutputWorkspace=self.getPropertyValue("OutputWorkspace")) self.setProperty("OutputWorkspace", output)
def reduceToPowder(ws, OutputWorkspace, cal=None, target='Theta', XMin=10, XMax=135, NumberBins=2500, normaliseBy='Monitor'): ConvertSpectrumAxis(InputWorkspace=ws, Target=target, OutputWorkspace=OutputWorkspace) Transpose(InputWorkspace=OutputWorkspace, OutputWorkspace=OutputWorkspace) ResampleX(InputWorkspace=OutputWorkspace, OutputWorkspace=OutputWorkspace, XMin=XMin, XMax=XMax, NumberBins=NumberBins) if cal is not None: CopyInstrumentParameters(ws, cal) ConvertSpectrumAxis(InputWorkspace=cal, Target=target, OutputWorkspace='__cal') Transpose(InputWorkspace='__cal', OutputWorkspace='__cal') ResampleX(InputWorkspace='__cal', OutputWorkspace='__cal', XMin=XMin, XMax=XMax, NumberBins=NumberBins) Divide(LHSWorkspace=OutputWorkspace, RHSWorkspace='__cal', OutputWorkspace=OutputWorkspace) DeleteWorkspace('__cal') if normaliseBy == "Monitor": ws_monitor = mtd[ws].run().getProtonCharge() cal_monitor = mtd[cal].run().getProtonCharge() Scale(InputWorkspace=OutputWorkspace, OutputWorkspace=OutputWorkspace, Factor=cal_monitor / ws_monitor) elif normaliseBy == "Time": ws_duration = mtd[ws].run().getLogData('duration').value cal_duration = mtd[cal].run().getLogData('duration').value Scale(InputWorkspace=OutputWorkspace, OutputWorkspace=OutputWorkspace, Factor=cal_duration / ws_duration) return OutputWorkspace
def test_computeincoherentdos(self): ws = CreateSampleWorkspace() # Will fail unless the input workspace has Q and DeltaE axes. with self.assertRaises(RuntimeError): ws_DOS = ComputeIncoherentDOS(ws) ws = CreateSampleWorkspace(XUnit = 'DeltaE') with self.assertRaises(RuntimeError): ws_DOS = ComputeIncoherentDOS(ws) # Creates a workspace with two optic phonon modes at +E and -E with Q^2 dependence and population correct for T=300K ws = self.createPhononWS(300, 5, 'DeltaE') # This should work! ws_DOS = ComputeIncoherentDOS(ws) self.assertEqual(ws_DOS.getAxis(0).getUnit().unitID(), 'DeltaE') self.assertEqual(ws_DOS.getNumberHistograms(), 1) # Checks that it works if the workspace has |Q| along x instead of y, and converts energy to wavenumber ws = Transpose(ws) ws_DOS = ComputeIncoherentDOS(ws, Temperature = 300, EnergyBinning = '-20, 0.2, 20', Wavenumbers = True) self.assertEqual(ws_DOS.getAxis(0).getUnit().unitID(), 'DeltaE_inWavenumber') self.assertEqual(ws_DOS.blocksize(), 200) # Checks that the Bose factor correction is ok. dos_eplus = np.max(ws_DOS.readY(0)[100:200]) dos_eminus = np.max(ws_DOS.readY(0)[:100]) self.assertAlmostEqual(dos_eplus / dos_eminus, 1., places=1) # Check that unit conversion from cm^-1 to meV works and also that conversion to states/meV is done ws = self.convertToWavenumber(ws) SetSampleMaterial(ws, 'Al') ws_DOSn = ComputeIncoherentDOS(ws, EnergyBinning = '-160, 1.6, 160', StatesPerEnergy = True) self.assertTrue('states' in ws_DOSn.YUnitLabel()) self.assertEqual(ws_DOSn.getAxis(0).getUnit().unitID(), 'DeltaE') material = ws.sample().getMaterial() factor = material.relativeMolecularMass() / (material.totalScatterXSection() * 1000) * 4 * np.pi self.assertAlmostEqual(np.max(ws_DOSn.readY(0)) / (np.max(ws_DOS.readY(0))*factor), 1., places=1)
def _resample_calibration( self, current_workspace, mask_name, x_min, x_max, ): """Perform resample on calibration""" cal = self.getProperty("CalibrationWorkspace").value target = self.getProperty("Target").value e_fixed = self.getProperty("EFixed").value number_bins = self.getProperty("NumberBins").value _ws_cal = ExtractUnmaskedSpectra( InputWorkspace=cal, MaskWorkspace=mask_name, EnableLogging=False ) if isinstance(mtd["_ws_cal"], IEventWorkspace): _ws_cal = Integration(InputWorkspace=_ws_cal, EnableLogging=False) CopyInstrumentParameters( InputWorkspace=current_workspace, OutputWorkspace=_ws_cal, EnableLogging=False, ) _ws_cal = ConvertSpectrumAxis( InputWorkspace=_ws_cal, Target=target, EFixed=e_fixed, EnableLogging=False, ) _ws_cal = Transpose(InputWorkspace=_ws_cal, EnableLogging=False) return ResampleX( InputWorkspace=_ws_cal, XMin=x_min, XMax=x_max, NumberBins=number_bins, EnableLogging=False, )
def test_2d_scanning_workspace(self): input_ws = CreateSampleWorkspace(NumMonitors=0, NumBanks=3, BankPixelWidth=2, XMin=0, XMax=5, BinWidth=1, NumScanPoints=7) calibration_x = np.array([0,1,2,0,1,2,0,1,2,0,1,2]) calibration_y = np.arange(12) calibration_ws = CreateWorkspace(DataX=calibration_x, DataY=calibration_y, Nspec=4) calibrated_ws = ApplyDetectorScanEffCorr(input_ws, calibration_ws) tmp = Transpose(calibration_ws) tmp = tmp.extractY().flatten() to_multiply = np.repeat(tmp, 5*7) to_multiply = np.reshape(to_multiply, [7*12,5]) for det in range(7*12): for bin in range(5): self.assertEquals(calibrated_ws.readY(det)[bin], input_ws.readY(det)[bin] * to_multiply[det][bin])
def extract_roi_matrix(workspace: MatrixWorkspace, xmin: float, xmax: float, ymin: float, ymax: float, transpose: bool, roi_name: str, log_algorithm_calls: bool = True): """ Assuming a MatrixWorkspace extract a 2D region from it. :param workspace: A MatrixWorkspace :param xmin: X min for bounded region :param xmax: X max for bounded region :param ymin: Y min for bounded region :param ymax: Y max for bounded region :param transpose: If true then the region bounds are transposed from the orientation of the workspace :param roi_name: Name of the result workspace :param log_algorithm_calls: Log the algorithm call or be silent """ yaxis = workspace.getAxis(1) if yaxis.isSpectra(): roi = _extract_roi_spectra_axis(workspace, xmin, xmax, ymin, ymax, roi_name, log_algorithm_calls) elif yaxis.isNumeric(): roi = _extract_roi_numeric_axis(workspace, xmin, xmax, ymin, ymax, roi_name, log_algorithm_calls) else: raise RuntimeError("Unknown vertical axis type") if transpose: roi = Transpose(InputWorkspace=roi_name, OutputWorkspace=roi_name) return roi
def _subtractFlatBkg(self, ws): """Return a workspace where a flat background has been subtracted from ws.""" method = self.getProperty(Prop.BKG_METHOD).value if method == BkgMethod.OFF: return ws clonedWSName = self._names.withSuffix('cloned_for_flat_bkg') clonedWS = CloneWorkspace( InputWorkspace=ws, OutputWorkspace=clonedWSName, EnableLogging=self._subalgLogging ) transposedWSName = self._names.withSuffix('transposed_clone') transposedWS = Transpose( InputWorkspace=clonedWS, OutputWorkspace=transposedWSName, EnableLogging=self._subalgLogging ) self._cleanup.cleanup(clonedWS) ranges = self._flatBkgRanges(ws) polynomialDegree = 0 if self.getProperty(Prop.BKG_METHOD).value == BkgMethod.CONSTANT else 1 transposedBkgWSName = self._names.withSuffix('transposed_flat_background') transposedBkgWS = CalculatePolynomialBackground( InputWorkspace=transposedWS, OutputWorkspace=transposedBkgWSName, Degree=polynomialDegree, XRanges=ranges, CostFunction='Unweighted least squares', EnableLogging=self._subalgLogging ) self._cleanup.cleanup(transposedWS) bkgWSName = self._names.withSuffix('flat_background') bkgWS = Transpose( InputWorkspace=transposedBkgWS, OutputWorkspace=bkgWSName, EnableLogging=self._subalgLogging ) self._cleanup.cleanup(transposedBkgWS) subtractedWSName = self._names.withSuffix('flat_background_subtracted') subtractedWS = Minus( LHSWorkspace=ws, RHSWorkspace=bkgWS, OutputWorkspace=subtractedWSName, EnableLogging=self._subalgLogging ) self._cleanup.cleanup(ws) self._cleanup.cleanup(bkgWS) return subtractedWS
def test_plotSofQW_transposed(self): wsName = 'ws' CloneWorkspace(self._sqw, OutputWorkspace=wsName) Transpose(wsName, OutputWorkspace=wsName) kwargs = {'workspace': wsName} testhelpers.assertRaisesNothing(self, directtools.plotSofQW, **kwargs) DeleteWorkspace(wsName) kwargs = {'workspace': self._sqw} testhelpers.assertRaisesNothing(self, directtools.plotSofQW, **kwargs)
def _locate_global_xlimit(self): """Find the global bin from all spectrum""" input_workspaces = self.getProperty("InputWorkspace").value mask = self.getProperty("MaskWorkspace").value maks_angle = self.getProperty("MaskAngle").value target = self.getProperty("Target").value e_fixed = self.getProperty("EFixed").value # NOTE: # Due to range difference among incoming spectra, a common bin para is needed # such that all data can be binned exactly the same way. _xMin, _xMax = 1e16, -1e16 # BEGIN_FOR: located_global_xMin&xMax for n, _wsn in enumerate(input_workspaces): _ws = AnalysisDataService.retrieve(_wsn) _mskn = f"__mask_{n}" self.temp_workspace_list.append(_mskn) ExtractMask(_ws, OutputWorkspace=_mskn, EnableLogging=False) if maks_angle != Property.EMPTY_DBL: MaskAngle( Workspace=_mskn, MinAngle=maks_angle, Angle="Phi", EnableLogging=False, ) if mask is not None: BinaryOperateMasks( InputWorkspace1=_mskn, InputWorkspace2=mask, OperationType="OR", OutputWorkspace=_mskn, EnableLogging=False, ) _ws_tmp = ExtractUnmaskedSpectra( InputWorkspace=_ws, MaskWorkspace=_mskn, EnableLogging=False ) if isinstance(mtd["_ws_tmp"], IEventWorkspace): _ws_tmp = Integration(InputWorkspace=_ws_tmp, EnableLogging=False) _ws_tmp = ConvertSpectrumAxis( InputWorkspace=_ws_tmp, Target=target, EFixed=e_fixed, EnableLogging=False, ) _ws_tmp = Transpose( InputWorkspace=_ws_tmp, OutputWorkspace=f"__ws_{n}", EnableLogging=False ) _xMin = min(_xMin, _ws_tmp.readX(0).min()) _xMax = max(_xMax, _ws_tmp.readX(0).max()) # END_FOR: located_global_xMin&xMax return _xMin, _xMax
def convertToWavenumber(self, ws): mev2cm = (constants.elementary_charge / 1000) / (constants.h * constants.c * 100) u0 = ws.getAxis(0).getUnit().unitID() u1 = ws.getAxis(1).getUnit().unitID() if u0 == 'DeltaE' or u1 == 'DeltaE': if u0 == 'MomentumTransfer': ws = Transpose(ws) ws.getAxis(0).setUnit('DeltaE_inWavenumber') ws = ScaleX(ws, mev2cm) ws = Scale(ws, 1/mev2cm) if u0 == 'MomentumTransfer': ws = Transpose(ws) return ws
def _transpose(self, mainWS, wsNames, wsCleanup, subalgLogging): """Transpose the final output workspace.""" transposing = self.getProperty(common.PROP_TRANSPOSE_SAMPLE_OUTPUT).value if transposing == common.TRANSPOSING_OFF: return mainWS transposedWSName = wsNames.withSuffix('transposed') transposedWS = Transpose(InputWorkspace=mainWS, OutputWorkspace=transposedWSName, EnableLogging=subalgLogging) wsCleanup.cleanup(mainWS) return transposedWS
def convert_to_2theta(ws_name, num_bins=1000): """ """ # duplicate for vanadium vanadium = CloneWorkspace(InputWorkspace=ws_name, OutputWorkspace='vanadium') # transfer to 2theta for data ConvertSpectrumAxis(InputWorkspace=ws_name, OutputWorkspace=ws_name, Target='Theta') Transpose(InputWorkspace=ws_name, OutputWorkspace=ws_name) ResampleX(InputWorkspace=ws_name, OutputWorkspace=ws_name, NumberBins=num_bins, PreserveEvents=False) # vanadium: set to 1 for now time_van_start = time.time() for iws in range(vanadium.getNumberHistograms()): vanadium.dataY(iws)[0] = 1. time_van_stop = time.time() ConvertSpectrumAxis(InputWorkspace='vanadium', OutputWorkspace='vanadium', Target='Theta') Transpose(InputWorkspace='vanadium', OutputWorkspace='vanadium') ResampleX(InputWorkspace='vanadium', OutputWorkspace='vanadium', NumberBins=num_bins, PreserveEvents=False) norm_ws_name = ws_name + '_normalized' Divide(LHSWorkspace=ws_name, RHSWorkspace='vanadium', OutputWorkspace=norm_ws_name) print('Create vanadium workspace : {} seconds'.format(time_van_stop - time_van_start)) return norm_ws_name
def PyExec(self): input_ws = self.getProperty("InputWorkspace").value eff_ws = self.getProperty("DetectorEfficiencyWorkspace").value transposed = Transpose(InputWorkspace=eff_ws, StoreInADS=False) efficiencies = transposed.extractY().flatten() errors = transposed.extractE().flatten() n_hist = input_ws.getNumberHistograms() if n_hist % efficiencies.size != 0: raise ValueError( 'Number of histograms in input workspace is not a multiple of number of entries in detector efficiency ' 'workspace.') n_time_indexes = n_hist / efficiencies.size to_multiply = CreateWorkspace(DataY=np.repeat(efficiencies, n_time_indexes), DataE=np.repeat(errors, n_time_indexes), DataX=np.zeros(n_hist), NSpec=n_hist, StoreInADS=False) output = Multiply( LHSWorkspace=input_ws, RHSWorkspace=to_multiply, OutputWorkspace=self.getPropertyValue("OutputWorkspace")) self.setProperty("OutputWorkspace", output)
def extract_cuts_matrix(workspace: MatrixWorkspace, xmin: float, xmax: float, ymin: float, ymax: float, xcut_name: str, ycut_name: str, log_algorithm_calls: bool = True): """ Assuming a MatrixWorkspace with vertical numeric axis, extract 1D cuts from the region defined by the given parameters :param workspace: A MatrixWorkspace with a vertical NumericAxis :param xmin: X min for bounded region :param xmax: X max for bounded region :param ymin: Y min for bounded region :param ymax: Y max for bounded region :param xcut_name: Name of the X cut. Empty indicates it should be skipped :param ycut_name: Name of the Y cut. Empty indicates it should be skipped :param log_algorithm_calls: Log the algorithm call or be silent """ tmp_crop_region = '__tmp_sv_region_extract' transpose = False roi = extract_roi_matrix(workspace, xmin, xmax, ymin, ymax, transpose, tmp_crop_region, log_algorithm_calls) # perform ycut first so xcut can reuse tmp workspace for rebinning if necessary if ycut_name: Rebin(InputWorkspace=roi, OutputWorkspace=ycut_name, Params=[xmin, xmax - xmin, xmax], EnableLogging=log_algorithm_calls) Transpose(InputWorkspace=ycut_name, OutputWorkspace=ycut_name, EnableLogging=log_algorithm_calls) if xcut_name: if not roi.isCommonBins(): # rebin to a common grid using the resolution from the spectrum # with the lowest resolution to avoid overbinning roi = _rebin_to_common_grid(roi, xmin, xmax, log_algorithm_calls) SumSpectra(InputWorkspace=roi, OutputWorkspace=xcut_name, EnableLogging=log_algorithm_calls) try: DeleteWorkspace(tmp_crop_region, EnableLogging=log_algorithm_calls) except ValueError: pass
def _to_spectrum_axis(self, workspace_in, workspace_out, mask, instrument_donor=None): target = self.getProperty("Target").value wavelength = self.getProperty("Wavelength").value e_fixed = UnitConversion.run('Wavelength', 'Energy', wavelength, 0, 0, 0, Elastic, 0) ExtractUnmaskedSpectra( InputWorkspace=workspace_in, OutputWorkspace=workspace_out, MaskWorkspace=mask, EnableLogging=False, ) if isinstance(mtd[workspace_out], IEventWorkspace): Integration( InputWorkspace=workspace_out, OutputWorkspace=workspace_out, EnableLogging=False, ) if instrument_donor: CopyInstrumentParameters( InputWorkspace=instrument_donor, OutputWorkspace=workspace_out, EnableLogging=False, ) ConvertSpectrumAxis( InputWorkspace=workspace_out, OutputWorkspace=workspace_out, Target=target, EFixed=e_fixed, EnableLogging=False, ) Transpose( InputWorkspace=workspace_out, OutputWorkspace=workspace_out, EnableLogging=False, ) return workspace_out
def test_computation_transposed_QW(self): energyBins = np.arange(-7., 7., 0.13) qs = np.array([2.15, 2.25]) ws = self.unitySQWSingleHistogram(energyBins, qs) ws = Transpose(ws, StoreInADS=False) dos = ComputeIncoherentDOS(ws, EnergyBinning='Emin, Emax', StoreInADS=False) self.assertEqual(dos.getNumberHistograms(), 1) self.assertEqual(dos.getAxis(0).getUnit().unitID(), 'DeltaE') dos_Xs = dos.readX(0) self.assertEqual(len(dos_Xs), len(energyBins)) dos_Ys = dos.readY(0) dos_Es = dos.readE(0) g = self.compute(qs, energyBins) np.testing.assert_equal(dos_Xs, energyBins) for i in range(len(dos_Ys)): self.assertAlmostEquals(dos_Ys[i], g[i]) self.assertAlmostEquals(dos_Es[i], g[i])
def get_data_y(ws_name, transpose): """ read data Y of a workspace :param ws_name: :param transpose: if the workspace is N x 1, then dimension == 1 means that workspace will be transposed for exporting data :return: """ if transpose == 1: ws_name_temp = '{}_transposed'.format(ws_name) if not workspace_exists(ws_name): Transpose(InputWorkspace=ws_name, OutputWorkspace=ws_name_temp) transpose_ws = retrieve_workspace(ws_name_temp) data_y = transpose_ws.readY(0) else: raise NotImplementedError('It has not been implemented to read 1 X N array') return data_y
def create_slice(file_path, plot_name): import mslice.cli as mc import matplotlib.pyplot as plt import numpy as np ws_name = plot_name.replace('.', '_') ws = mc.Load(Filename=file_path, OutputWorkspace=ws_name) fig = plt.figure() # Using Mantid projection instead of MSlice to ensure it works headless ax = fig.add_subplot(111, projection="mantid") slice_ws = mc.Slice(ws) mantid_slice = Transpose(slice_ws.raw_ws) mesh = ax.pcolormesh(mantid_slice, cmap="viridis") # Restrict color range to be 1/5 of the max counts in the range between 0.1 and 0.9 Ei en = ws.get_coordinates()['Energy transfer'] en_id = np.where((en > ws.e_fixed/10) * (en < ws.e_fixed*0.9)) mesh.set_clim(0.0, np.max(ws.get_signal()[:,en_id]) / 3) cb = plt.colorbar(mesh, ax=ax) cb.set_label('Intensity (arb. units)', labelpad=20, rotation=270, picker=5) ax.set_title(plot_name) return fig
def _transpose(workspace): return Transpose(InputWorkspace=workspace, OutputWorkspace="__transposed", StoreInADS=False, EnableLogging=False)
def PyExec(self): data = self.getProperty("InputWorkspace").value cal = self.getProperty("CalibrationWorkspace").value bkg = self.getProperty("BackgroundWorkspace").value mask = self.getProperty("MaskWorkspace").value target = self.getProperty("Target").value eFixed = self.getProperty("EFixed").value xMin = self.getProperty("XMin").value xMax = self.getProperty("XMax").value numberBins = self.getProperty("NumberBins").value normaliseBy = self.getProperty("NormaliseBy").value maskAngle = self.getProperty("MaskAngle").value outWS = self.getPropertyValue("OutputWorkspace") data_scale = 1 cal_scale = 1 bkg_scale = 1 if normaliseBy == "Monitor": data_scale = data.run().getProtonCharge() elif normaliseBy == "Time": data_scale = data.run().getLogData('duration').value ExtractMask(data, OutputWorkspace='__mask_tmp', EnableLogging=False) if maskAngle != Property.EMPTY_DBL: MaskAngle(Workspace='__mask_tmp', MinAngle=maskAngle, Angle='Phi', EnableLogging=False) if mask is not None: BinaryOperateMasks(InputWorkspace1='__mask_tmp', InputWorkspace2=mask, OperationType='OR', OutputWorkspace='__mask_tmp', EnableLogging=False) ExtractUnmaskedSpectra(InputWorkspace=data, MaskWorkspace='__mask_tmp', OutputWorkspace='__data_tmp', EnableLogging=False) if isinstance(mtd['__data_tmp'], IEventWorkspace): Integration(InputWorkspace='__data_tmp', OutputWorkspace='__data_tmp', EnableLogging=False) ConvertSpectrumAxis(InputWorkspace='__data_tmp', Target=target, EFixed=eFixed, OutputWorkspace=outWS, EnableLogging=False) Transpose(InputWorkspace=outWS, OutputWorkspace=outWS, EnableLogging=False) ResampleX(InputWorkspace=outWS, OutputWorkspace=outWS, XMin=xMin, XMax=xMax, NumberBins=numberBins, EnableLogging=False) if cal is not None: ExtractUnmaskedSpectra(InputWorkspace=cal, MaskWorkspace='__mask_tmp', OutputWorkspace='__cal_tmp', EnableLogging=False) if isinstance(mtd['__cal_tmp'], IEventWorkspace): Integration(InputWorkspace='__cal_tmp', OutputWorkspace='__cal_tmp', EnableLogging=False) CopyInstrumentParameters(data, '__cal_tmp', EnableLogging=False) ConvertSpectrumAxis(InputWorkspace='__cal_tmp', Target=target, EFixed=eFixed, OutputWorkspace='__cal_tmp', EnableLogging=False) Transpose(InputWorkspace='__cal_tmp', OutputWorkspace='__cal_tmp', EnableLogging=False) ResampleX(InputWorkspace='__cal_tmp', OutputWorkspace='__cal_tmp', XMin=xMin, XMax=xMax, NumberBins=numberBins, EnableLogging=False) Divide(LHSWorkspace=outWS, RHSWorkspace='__cal_tmp', OutputWorkspace=outWS, EnableLogging=False) if normaliseBy == "Monitor": cal_scale = cal.run().getProtonCharge() elif normaliseBy == "Time": cal_scale = cal.run().getLogData('duration').value Scale(InputWorkspace=outWS, OutputWorkspace=outWS, Factor=cal_scale / data_scale, EnableLogging=False) if bkg is not None: ExtractUnmaskedSpectra(InputWorkspace=bkg, MaskWorkspace='__mask_tmp', OutputWorkspace='__bkg_tmp', EnableLogging=False) if isinstance(mtd['__bkg_tmp'], IEventWorkspace): Integration(InputWorkspace='__bkg_tmp', OutputWorkspace='__bkg_tmp', EnableLogging=False) CopyInstrumentParameters(data, '__bkg_tmp', EnableLogging=False) ConvertSpectrumAxis(InputWorkspace='__bkg_tmp', Target=target, EFixed=eFixed, OutputWorkspace='__bkg_tmp', EnableLogging=False) Transpose(InputWorkspace='__bkg_tmp', OutputWorkspace='__bkg_tmp', EnableLogging=False) ResampleX(InputWorkspace='__bkg_tmp', OutputWorkspace='__bkg_tmp', XMin=xMin, XMax=xMax, NumberBins=numberBins, EnableLogging=False) if cal is not None: Divide(LHSWorkspace='__bkg_tmp', RHSWorkspace='__cal_tmp', OutputWorkspace='__bkg_tmp', EnableLogging=False) if normaliseBy == "Monitor": bkg_scale = bkg.run().getProtonCharge() elif normaliseBy == "Time": bkg_scale = bkg.run().getLogData('duration').value Scale(InputWorkspace='__bkg_tmp', OutputWorkspace='__bkg_tmp', Factor=cal_scale / bkg_scale, EnableLogging=False) Scale(InputWorkspace='__bkg_tmp', OutputWorkspace='__bkg_tmp', Factor=self.getProperty('BackgroundScale').value, EnableLogging=False) Minus(LHSWorkspace=outWS, RHSWorkspace='__bkg_tmp', OutputWorkspace=outWS, EnableLogging=False) self.setProperty("OutputWorkspace", outWS) # remove temp workspaces [ DeleteWorkspace(ws, EnableLogging=False) for ws in self.temp_workspace_list if mtd.doesExist(ws) ]
def reduce_to_2theta(hb2b_builder, pixel_matrix, hb2b_data_ws_name, counts_array, mask_vec, mask_ws_name, num_bins=1000): """ Reduce to 2theta with Masks :param hb2b_builder: :param pixel_matrix: :param hb2b_data_ws_name: :param counts_array: :param mask_vec: :param num_bins: :return: """ # reduce by PyRS if False: pyrs_raw_ws = mtd[pyrs_raw_name] vec_counts = pyrs_raw_ws.readY(0) else: vec_counts = counts_array.astype('float64') # mask if mask_vec is not None: print(mask_vec.dtype) vec_counts.astype('float64') mask_vec.astype('float64') vec_counts *= mask_vec # reduce bin_edgets, histogram = hb2b_builder.reduce_to_2theta_histogram( pixel_matrix, vec_counts, num_bins) # create workspace pyrs_reduced_name = '{}_pyrs_reduced'.format(hb2b_data_ws_name) CreateWorkspace(DataX=bin_edgets, DataY=histogram, NSpec=1, OutputWorkspace=pyrs_reduced_name) SaveNexusProcessed(InputWorkspace=pyrs_reduced_name, Filename='{}.nxs'.format(pyrs_reduced_name), Title='PyRS reduced: {}'.format(hb2b_data_ws_name)) if True: # Mantid # transfer to 2theta for data two_theta_ws_name = '{}_2theta'.format(hb2b_data_ws_name) # Mask if mask_ws_name: # Multiply by masking workspace masked_ws_name = '{}_masked'.format(hb2b_data_ws_name) Multiply(LHSWorkspace=hb2b_data_ws_name, RHSWorkspace=mask_ws_name, OutputWorkspace=masked_ws_name, ClearRHSWorkspace=False) hb2b_data_ws_name = masked_ws_name SaveNexusProcessed(InputWorkspace=hb2b_data_ws_name, Filename='{}_raw.nxs'.format(hb2b_data_ws_name)) # END-IF # # this is for test only! # ConvertSpectrumAxis(InputWorkspace=hb2b_data_ws_name, OutputWorkspace=two_theta_ws_name, Target='Theta', # OrderAxis=False) # Transpose(InputWorkspace=two_theta_ws_name, OutputWorkspace=two_theta_ws_name) # two_theta_ws = mtd[two_theta_ws_name] # for i in range(10): # print ('{}: x = {}, y = {}'.format(i, two_theta_ws.readX(0)[i], two_theta_ws.readY(0)[i])) # for i in range(10010, 10020): # print ('{}: x = {}, y = {}'.format(i, two_theta_ws.readX(0)[i], two_theta_ws.readY(0)[i])) ConvertSpectrumAxis(InputWorkspace=hb2b_data_ws_name, OutputWorkspace=two_theta_ws_name, Target='Theta') Transpose(InputWorkspace=two_theta_ws_name, OutputWorkspace=two_theta_ws_name) # final: mantid_reduced_name = '{}_mtd_reduced'.format(hb2b_data_ws_name) ResampleX(InputWorkspace=two_theta_ws_name, OutputWorkspace=mantid_reduced_name, NumberBins=num_bins, PreserveEvents=False) mantid_ws = mtd[mantid_reduced_name] SaveNexusProcessed( InputWorkspace=mantid_reduced_name, Filename='{}.nxs'.format(mantid_reduced_name), Title='Mantid reduced: {}'.format(hb2b_data_ws_name)) plt.plot(mantid_ws.readX(0), mantid_ws.readY(0), color='blue', mark='o') # END-IF plt.plot(bin_edgets[:-1], histogram, color='red') plt.show() return
def _resample_background( self, current_background, current_workspace, make_name, x_min, x_max, resmapled_calibration, ): """Perform resample on given background""" cal = self.getProperty("CalibrationWorkspace").value target = self.getProperty("Target").value e_fixed = self.getProperty("EFixed").value number_bins = self.getProperty("NumberBins").value _ws_bkg = ExtractUnmaskedSpectra( InputWorkspace=current_background, MaskWorkspace=make_name, EnableLogging=False, ) if isinstance(mtd["_ws_bkg"], IEventWorkspace): _ws_bkg = Integration(InputWorkspace=_ws_bkg, EnableLogging=False) CopyInstrumentParameters( InputWorkspace=current_workspace, OutputWorkspace=_ws_bkg, EnableLogging=False, ) _ws_bkg = ConvertSpectrumAxis( InputWorkspace=_ws_bkg, Target=target, EFixed=e_fixed, EnableLogging=False, ) _ws_bkg = Transpose(InputWorkspace=_ws_bkg, EnableLogging=False) _ws_bkg_resampled = ResampleX( InputWorkspace=_ws_bkg, XMin=x_min, XMax=x_max, NumberBins=number_bins, EnableLogging=False, ) if cal is not None: _ws_bkg_resampled = Divide( LHSWorkspace=_ws_bkg_resampled, RHSWorkspace=resmapled_calibration, EnableLogging=False, ) _ws_bkg_resampled = Scale( InputWorkspace=_ws_bkg_resampled, Factor=self._get_scale(cal) / self._get_scale(current_background), EnableLogging=False, ) _ws_bkg_resampled = Scale( InputWorkspace=_ws_bkg_resampled, Factor=self.getProperty("BackgroundScale").value, EnableLogging=False, ) return _ws_bkg_resampled