Skip to content
Snippets Groups Projects
Commit 6bd6cc0e authored by Mathieu Doucet's avatar Mathieu Doucet
Browse files

Merge pull request #13755 from mantidproject/13572_imprv_SavePlot1DAsJson

Improve saveplot1dasjson
parents 6fe63eb1 5a55ef76
No related merge requests found
#pylint: disable=no-init,unused-variable
#pylint: disable=no-init,unused-variable,invalid-name,bare-except
from mantid.api import *
from mantid.kernel import *
......@@ -76,30 +76,47 @@ class SavePlot1DAsJson(PythonAlgorithm):
return
def _serialize(self, workspace, plotname):
wname = plotname or workspace.getName()
pname = plotname or workspace.getName()
# init dictionary
ishist = workspace.isHistogramData()
plottype = "histogram" if ishist else "point"
serialized = {"type": plottype}
# helper
label = lambda axis: "%s (%s)" % (
axis.getUnit().caption(),
axis.getUnit().symbol() or 1,
serialized = dict(
type = plottype,
data = dict(),
)
# loop over spectra
for i in range(workspace.getNumberHistograms()):
k = "%s%s" % (wname, i)
value = dict(
x=list(workspace.readX(i)),
y=list(workspace.readY(i)),
e=list(workspace.readE(i)),
xlabel=label(workspace.getAxis(0)),
ylabel=label(workspace.getAxis(1)),
title="long title of %s" % k,
)
serialized[k] = value
spectrum_no = workspace.getSpectrum(i).getSpectrumNo()
# Why do we need label?
# label = "%s_spectrum_%d" % (pname, spectrum_no)
# labels.append(label)
# or title?
# title = "%s - spectrum %d" % (workspace.getTitle(), spectrum_no)
arr = [
list(workspace.readX(i)),
list(workspace.readY(i)),
list(workspace.readE(i)),
]
serialized['data'][spectrum_no] = arr
continue
return serialized
# axes
# .. helper
label = lambda axis: axis.getUnit().caption()
def unit(axis):
s = axis.getUnit().symbol()
try:
return s.latex()
except:
return '%s' % s
axes = dict(
xlabel=label(workspace.getAxis(0)),
ylabel=label(workspace.getAxis(1)),
xunit = unit(workspace.getAxis(0)),
# yunit = unit(workspace.getAxis(1)),
yunit = workspace.YUnitLabel(),
)
serialized['axes'] = axes
return {pname: serialized}
# Register algorithm with Mantid
......
#pylint: disable=invalid-name,too-many-public-methods
#pylint: disable=invalid-name,too-many-public-methods,too-many-arguments
import unittest
import numpy as np
import mantid.simpleapi as api
......@@ -9,13 +9,13 @@ from mantid.api import AnalysisDataService
import os, json
class SaveVulcanGSSTest(unittest.TestCase):
class SavePlot1DAsJsonTest(unittest.TestCase):
def test_save_one_curve(self):
""" Test to Save one curve
"""
datawsname = "TestOneCurve"
E, I, err = self._createOneCurve(datawsname)
datawsname = "constant energy cut"
E, I, err = self._createOneQCurve(datawsname)
# Execute
out_path = "tempout_curve.json"
......@@ -26,11 +26,9 @@ class SaveVulcanGSSTest(unittest.TestCase):
# executed?
self.assertTrue(alg_test.isExecuted())
# Verify ....
d = json.load(open(out_path))
d0 = d[datawsname+'0'] # plots are numbered
np.testing.assert_array_equal(d0['x'], E)
np.testing.assert_array_equal(d0['y'], I)
np.testing.assert_array_equal(d0['e'], err)
d = json.load(open(out_path))[datawsname]
self.assertEqual(d['type'], 'point')
self._checkData(d, E, I, err)
# Delete the output file
os.remove(out_path)
return
......@@ -51,11 +49,8 @@ class SaveVulcanGSSTest(unittest.TestCase):
# Executed?
self.assertTrue(alg_test.isExecuted())
# Verify ....
d = json.load(open(out_path))
d0 = d[datawsname+'0'] # plots are numbered
np.testing.assert_array_equal(d0['x'], E)
np.testing.assert_array_equal(d0['y'], I)
np.testing.assert_array_equal(d0['e'], err)
d = json.load(open(out_path))[datawsname]
self._checkData(d, E, I, err)
# test overwrite
alg_test = run_algorithm(
"SavePlot1DAsJson",
......@@ -80,14 +75,9 @@ class SaveVulcanGSSTest(unittest.TestCase):
# executed?
self.assertTrue(alg_test.isExecuted())
# Verify ....
d = json.load(open(out_path))
d0 = d[datawsname+'0'] # plots are numbered
np.testing.assert_array_equal(d0['x'], E)
np.testing.assert_array_equal(d0['y'], I)
np.testing.assert_array_equal(d0['e'], err)
d1 = d[datawsname+'1'] #
np.testing.assert_array_equal(d1['y'], I2)
np.testing.assert_array_equal(d1['e'], err2)
d = json.load(open(out_path))[datawsname]
self._checkData(d, E, I, err)
self._checkData(d, E, I2, err2, ID="2")
# Delete the output file
os.remove(out_path)
return
......@@ -97,6 +87,7 @@ class SaveVulcanGSSTest(unittest.TestCase):
""" Test to Save one curve with a name specified by client
"""
datawsname = "TestOneCurve"
plotname = "myplot"
E, I, err = self._createOneCurve(datawsname)
# Execute
out_path = "tempout_curve_withname.json"
......@@ -104,36 +95,55 @@ class SaveVulcanGSSTest(unittest.TestCase):
"SavePlot1DAsJson",
InputWorkspace = datawsname,
JsonFilename = out_path,
PlotName = "myplot")
PlotName = plotname)
# executed?
self.assertTrue(alg_test.isExecuted())
# Verify ....
d = json.load(open(out_path))
plotname = "myplot"
d0 = d[plotname+'0'] # plots are numbered
np.testing.assert_array_equal(d0['x'], E)
np.testing.assert_array_equal(d0['y'], I)
np.testing.assert_array_equal(d0['e'], err)
d = json.load(open(out_path))[plotname]
self._checkData(d, E, I, err)
# Delete the output file
os.remove(out_path)
return
def _checkData(self, s, E, I, err, ID="1"):
d0 = s["data"][ID]
np.testing.assert_array_equal(d0[0], E)
np.testing.assert_array_equal(d0[1], I)
np.testing.assert_array_equal(d0[2], err)
return
def _createOneCurve(self, datawsname):
""" Create data workspace
"""
E = np.arange(-50, 50, 1.0)
E = np.arange(-50, 50, 10.0)
I = 1000 * np.exp(-E**2/10**2)
err = I ** .5
# create workspace
dataws = api.CreateWorkspace(
DataX = E, DataY = I, DataE = err, NSpec = 1,
UnitX = "Energy(meV)")
UnitX = "Energy")
# Add to data service
AnalysisDataService.addOrReplace(datawsname, dataws)
return E, I, err
def _createOneQCurve(self, datawsname):
""" Create data workspace
"""
Q = np.arange(0, 13, 1.0)
I = 1000 * np.exp(-Q**2/10**2)
err = I ** .5
# create workspace
dataws = api.CreateWorkspace(
DataX = Q, DataY = I, DataE = err, NSpec = 1,
UnitX = "Momentum")
# Add to data service
AnalysisDataService.addOrReplace(datawsname, dataws)
return Q, I, err
def _createOneHistogram(self, datawsname):
""" Create data workspace
"""
......
......@@ -26,12 +26,12 @@ Usage
import os, numpy as np
# prepare input
E = np.arange(-50, 50, 1.0)
E = np.arange(-50, 50, 10.0)
I = 1000 * np.exp(-E**2/10**2)
err = I ** .5
dataws = CreateWorkspace(
DataX = E, DataY = I, DataE = err, NSpec = 1,
UnitX = "Energy(meV)")
UnitX = "Energy")
# output path
out_json = "myplot.json"
# run algorithm
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment