Skip to content

Commit 2ed3eb4

Browse files
Merge pull request #133 from mantidproject/update-system-benchmark
Update benchmark for analysis system test
2 parents d28eb30 + 1a56094 commit 2ed3eb4

File tree

5 files changed

+11
-78
lines changed

5 files changed

+11
-78
lines changed

src/mvesuvio/analysis_reduction.py

Lines changed: 5 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
import numpy as np
22
import matplotlib.pyplot as plt
3-
from scipy import optimize
3+
import scipy
44
from mantid.simpleapi import mtd, CreateEmptyTableWorkspace, SumSpectra, \
55
CloneWorkspace, DeleteWorkspace, VesuvioCalculateGammaBackground, \
66
VesuvioCalculateMS, Scale, RenameWorkspace, Minus, CreateSampleShape, \
77
VesuvioThickness, Integration, Divide, Multiply, DeleteWorkspaces, \
88
CreateWorkspace
99

10-
from mvesuvio.util.analysis_helpers import histToPointData, loadConstants, \
11-
gaussian, lorentzian, numericalThirdDerivative
10+
from mvesuvio.util.analysis_helpers import loadConstants, numericalThirdDerivative
1211

1312
from dataclasses import dataclass
1413

@@ -69,10 +68,6 @@ def __init__(self, workspace, ip_file, h_ratio_to_lowest_mass, number_of_iterati
6968
self._table_fit_results = None
7069
self._fit_profiles_workspaces = {}
7170

72-
# Only used for system tests, remove once tests are updated
73-
self._run_hist_data = True
74-
self._run_norm_voigt = False
75-
7671

7772
def add_profiles(self, *args: NeutronComptonProfile):
7873
for profile in args:
@@ -152,9 +147,6 @@ def _update_workspace_data(self):
152147
self._dataY = self._workspace_being_fit.extractY()
153148
self._dataE = self._workspace_being_fit.extractE()
154149

155-
if self._run_hist_data: # Converts point data from workspaces to histogram data
156-
self._dataY, self._dataX, self._dataE = histToPointData(self._dataY, self._dataX, self._dataE)
157-
158150
self._set_up_kinematic_arrays()
159151

160152
self._fit_parameters = np.zeros((len(self._dataY), 3 * len(self._profiles) + 3))
@@ -593,7 +585,7 @@ def _fit_neutron_compton_profiles_to_row(self):
593585
for attr in ['intensity_bounds', 'width_bounds', 'center_bounds']:
594586
bounds.append(getattr(p, attr))
595587

596-
result = optimize.minimize(
588+
result = scipy.optimize.minimize(
597589
self.errorFunction,
598590
initial_parameters,
599591
method="SLSQP",
@@ -658,7 +650,7 @@ def _neutron_compton_profiles(self, pars):
658650
gaussRes, lorzRes = self.caculateResolutionForEachMass(centers)
659651
totalGaussWidth = np.sqrt(widths**2 + gaussRes**2)
660652

661-
JOfY = self.pseudoVoigt(self._y_space_arrays[self._row_being_fit] - centers, totalGaussWidth, lorzRes)
653+
JOfY = scipy.special.voigt_profile(self._y_space_arrays[self._row_being_fit] - centers, totalGaussWidth, lorzRes)
662654

663655
FSE = (
664656
-numericalThirdDerivative(self._y_space_arrays[self._row_being_fit], JOfY)
@@ -771,20 +763,6 @@ def calcLorentzianResolution(self, centers):
771763
return lorentzianResWidth
772764

773765

774-
def pseudoVoigt(self, x, sigma, gamma):
775-
"""Convolution between Gaussian with std sigma and Lorentzian with HWHM gamma"""
776-
fg, fl = 2.0 * sigma * np.sqrt(2.0 * np.log(2.0)), 2.0 * gamma
777-
f = 0.5346 * fl + np.sqrt(0.2166 * fl**2 + fg**2)
778-
eta = 1.36603 * fl / f - 0.47719 * (fl / f) ** 2 + 0.11116 * (fl / f) ** 3
779-
sigma_v, gamma_v = f / (2.0 * np.sqrt(2.0 * np.log(2.0))), f / 2.0
780-
pseudo_voigt = eta * lorentzian(x, gamma_v) + (1.0 - eta) * gaussian(x, sigma_v)
781-
782-
norm = (
783-
np.abs(np.trapz(pseudo_voigt, x, axis=1))[:, np.newaxis] if self._run_norm_voigt else 1
784-
)
785-
return pseudo_voigt / norm
786-
787-
788766
def _get_parsed_constraints(self):
789767

790768
parsed_constraints = []
@@ -836,8 +814,7 @@ def _replace_zero_columns_with_ncp_fit(self):
836814
OutputWorkspace=self._workspace_for_corrections.name() + "_CorrectionsInput"
837815
)
838816
for row in range(self._workspace_for_corrections.getNumberHistograms()):
839-
# TODO: Once the option to change point to hist is removed, remove [:len(ncp)]
840-
self._workspace_for_corrections.dataY(row)[self._zero_columns_boolean_mask] = ncp[row, self._zero_columns_boolean_mask[:len(ncp[row])]]
817+
self._workspace_for_corrections.dataY(row)[self._zero_columns_boolean_mask] = ncp[row, self._zero_columns_boolean_mask]
841818

842819
SumSpectra(
843820
InputWorkspace=self._workspace_for_corrections.name(),
@@ -1082,7 +1059,6 @@ def _set_results(self):
10821059
self.all_spec_best_par_chi_nit = np.array(allBestPar)
10831060
self.all_tot_ncp = np.array(allTotNcp)
10841061
self.all_ncp_for_each_mass = np.array(allIterNcp)
1085-
10861062
self.all_mean_widths = np.array(allMeanWidhts)
10871063
self.all_mean_intensities = np.array(allMeanIntensities)
10881064
self.all_std_widths = np.array(allStdWidths)
@@ -1091,14 +1067,6 @@ def _set_results(self):
10911067
def _save_results(self):
10921068
"""Saves all of the arrays stored in this object"""
10931069

1094-
maskedDetectorIdx = np.array(self._mask_spectra) - min(self._workspace_being_fit.getSpectrumNumbers())
1095-
1096-
# TODO: Take out nans next time when running original results
1097-
# Because original results were recently saved with nans, mask spectra with nans
1098-
self.all_spec_best_par_chi_nit[:, maskedDetectorIdx, :] = np.nan
1099-
self.all_ncp_for_each_mass[:, maskedDetectorIdx, :, :] = np.nan
1100-
self.all_tot_ncp[:, maskedDetectorIdx, :] = np.nan
1101-
11021070
if not self._save_results_path:
11031071
return
11041072

src/mvesuvio/util/analysis_helpers.py

Lines changed: 0 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -112,25 +112,6 @@ def extractWS(ws):
112112
return ws.extractX(), ws.extractY(), ws.extractE()
113113

114114

115-
def histToPointData(dataY, dataX, dataE):
116-
"""
117-
Used only when comparing with original results.
118-
Sets each dataY point to the center of bins.
119-
Last column of data is removed.
120-
Removed original scaling by bin widths
121-
"""
122-
123-
histWidths = dataX[:, 1:] - dataX[:, :-1]
124-
assert np.min(histWidths) == np.max(
125-
histWidths
126-
), "Histogram widths need to be the same length"
127-
128-
dataYp = dataY[:, :-1]
129-
dataEp = dataE[:, :-1]
130-
dataXp = dataX[:, :-1] + histWidths[0, 0] / 2
131-
return dataYp, dataXp, dataEp
132-
133-
134115
def loadConstants():
135116
"""Output: the mass of the neutron, final energy of neutrons (selected by gold foil),
136117
factor to change energies into velocities, final velocity of neutron and hbar"""
@@ -143,18 +124,6 @@ def loadConstants():
143124
return constants
144125

145126

146-
def gaussian(x, sigma):
147-
"""Gaussian centered at zero"""
148-
gauss = np.exp(-(x**2) / 2 / sigma**2)
149-
gauss /= np.sqrt(2.0 * np.pi) * sigma
150-
return gauss
151-
152-
153-
def lorentzian(x, gamma):
154-
"""Lorentzian centered at zero"""
155-
return gamma / np.pi / (x**2 + gamma**2)
156-
157-
158127
def numericalThirdDerivative(x, y):
159128
k6 = (- y[:, 12:] + y[:, :-12]) * 1
160129
k5 = (+ y[:, 11:-1] - y[:, 1:-11]) * 24
-296 KB
Binary file not shown.
6.09 KB
Binary file not shown.

tests/system/analysis/test_analysis.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -100,13 +100,13 @@ def test_nit(self):
100100
nptest.assert_almost_equal(self.orinit, self.optnit, decimal=-2)
101101

102102
def test_intensities(self):
103-
nptest.assert_almost_equal(self.oriintensities, self.optintensities, decimal=2)
103+
nptest.assert_almost_equal(self.oriintensities, self.optintensities, decimal=4)
104104

105105
def test_widths(self):
106-
nptest.assert_almost_equal(self.oriwidths, self.optwidths, decimal=2)
106+
nptest.assert_almost_equal(self.oriwidths, self.optwidths, decimal=4)
107107

108108
def test_centers(self):
109-
nptest.assert_almost_equal(self.oricenters, self.optcenters, decimal=1)
109+
nptest.assert_almost_equal(self.oricenters, self.optcenters, decimal=2)
110110

111111

112112
class TestNcp(unittest.TestCase):
@@ -116,15 +116,11 @@ def setUpClass(cls):
116116
cls.currentResults = AnalysisRunner.get_current_result()
117117

118118
def setUp(self):
119-
self.orincp = self.benchmarkResults["all_tot_ncp"][:, :, :-1]
120-
119+
self.orincp = self.benchmarkResults["all_tot_ncp"]
121120
self.optncp = self.currentResults.all_tot_ncp
122121

123122
def test_ncp(self):
124-
correctNansOri = np.where(
125-
(self.orincp == 0) & np.isnan(self.optncp), np.nan, self.orincp
126-
)
127-
nptest.assert_almost_equal(correctNansOri, self.optncp, decimal=4)
123+
nptest.assert_almost_equal(self.orincp, self.optncp, decimal=5)
128124

129125

130126
class TestMeanWidths(unittest.TestCase):
@@ -138,7 +134,7 @@ def setUp(self):
138134
self.optmeanwidths = self.currentResults.all_mean_widths
139135

140136
def test_widths(self):
141-
nptest.assert_almost_equal(self.orimeanwidths, self.optmeanwidths, decimal=5)
137+
nptest.assert_almost_equal(self.orimeanwidths, self.optmeanwidths, decimal=6)
142138

143139

144140
class TestMeanIntensities(unittest.TestCase):

0 commit comments

Comments
 (0)