Skip to content

Commit 0cde67c

Browse files
authored
1 parent 105e437 commit 0cde67c

File tree

1 file changed

+145
-9
lines changed

1 file changed

+145
-9
lines changed

finddata/publish_plot.py

Lines changed: 145 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ class Configuration(object):
1717
heavily abridged version of what is found in postprocessing.
1818
"""
1919
def __init__(self, config_file):
20-
if os.access(config_file, os.R_OK) == False:
20+
if os.access(config_file, os.R_OK) is False:
2121
raise RuntimeError("Configuration file doesn't exist or is not readable: %s" % config_file)
2222
with open(config_file, 'r') as cfg:
2323
json_encoded = cfg.read()
@@ -31,13 +31,14 @@ def __init__(self, config_file):
3131
self.publisher_username = config['publisher_username'] if 'publisher_username' in config else ''
3232
self.publisher_password = config['publisher_password'] if 'publisher_password' in config else ''
3333

34+
3435
def _determine_config_file(config_file):
3536
# put together the list of all choices
3637
choices = [config_file, CONFIG_FILE, CONFIG_FILE_ALTERNATE]
3738

3839
# filter out bad choices
3940
choices = [name for name in choices
40-
if not name is None]
41+
if name is not None]
4142
choices = [name for name in choices
4243
if len(name) > 0]
4344
choices = [name for name in choices
@@ -49,6 +50,7 @@ def _determine_config_file(config_file):
4950
else:
5051
return None
5152

53+
5254
def read_configuration(config_file=None):
5355
"""
5456
Returns a new configuration object for a given
@@ -62,6 +64,7 @@ def read_configuration(config_file=None):
6264
logging.info('Loading configuration \'%s\'' % config_file)
6365
return Configuration(config_file)
6466

67+
6568
def _loadDiv(filename):
6669
if not os.path.exists(filename):
6770
raise RuntimeError('\'%s\' does not exist' % filename)
@@ -70,21 +73,23 @@ def _loadDiv(filename):
7073
div = handle.read()
7174
return div
7275

76+
7377
def _getURL(url_template, instrument, run_number):
7478
import string
75-
url_template=string.Template(url_template)
79+
url_template = string.Template(url_template)
7680
url = url_template.substitute(instrument=instrument,
7781
run_number=str(run_number))
7882
return url
7983

84+
8085
def publish_plot(instrument, run_number, files, config=None):
8186
# read the configuration if one isn't provided
8287
if config is None:
8388
config = read_configuration()
8489
# verify that it has an attribute that matters
8590
try:
8691
config.publish_url
87-
except AttributeError: # assume that it is a filename
92+
except AttributeError: # assume that it is a filename
8893
config = read_configuration(config)
8994

9095
run_number = str(run_number)
@@ -103,17 +108,148 @@ def publish_plot(instrument, run_number, files, config=None):
103108
files=files, verify=False)
104109
return request
105110

111+
112+
def plot1d(run_number, data_list, data_names=None, x_title='', y_title='',
113+
x_log=False, y_log=False, instrument='', show_dx=True, title='', publish=True):
114+
"""
115+
Produce a 1D plot
116+
@param data_list: list of traces [ [x1, y1], [x2, y2], ...]
117+
@param data_names: name for each trace, for the legend
118+
"""
119+
from plotly.offline import plot
120+
import plotly.graph_objs as go
121+
122+
# Create traces
123+
if not isinstance(data_list, list):
124+
raise RuntimeError("plot1d: data_list parameter is expected to be a list")
125+
126+
# Catch the case where the list is in the format [x y]
127+
data = []
128+
show_legend = False
129+
if len(data_list) == 2 and not isinstance(data_list[0], list):
130+
label = ''
131+
if isinstance(data_names, list) and len(data_names) == 1:
132+
label = data_names[0]
133+
show_legend = True
134+
data = [go.Scatter(name=label, x=data_list[0], y=data_list[1])]
135+
else:
136+
for i in range(len(data_list)):
137+
label = ''
138+
if isinstance(data_names, list) and len(data_names) == len(data_list):
139+
label = data_names[i]
140+
show_legend = True
141+
err_x = {}
142+
err_y = {}
143+
if len(data_list[i]) >= 3:
144+
err_y = dict(type='data', array=data_list[i][2], visible=True)
145+
if len(data_list[i]) >= 4:
146+
err_x = dict(type='data', array=data_list[i][3], visible=True)
147+
if show_dx is False:
148+
err_x['thickness'] = 0
149+
data.append(go.Scatter(name=label, x=data_list[i][0], y=data_list[i][1],
150+
error_x=err_x, error_y=err_y))
151+
152+
x_layout = dict(title=x_title, zeroline=False, exponentformat="power",
153+
showexponent="all", showgrid=True,
154+
showline=True, mirror="all", ticks="inside")
155+
if x_log:
156+
x_layout['type'] = 'log'
157+
y_layout = dict(title=y_title, zeroline=False, exponentformat="power",
158+
showexponent="all", showgrid=True,
159+
showline=True, mirror="all", ticks="inside")
160+
if y_log:
161+
y_layout['type'] = 'log'
162+
163+
layout = go.Layout(
164+
showlegend=show_legend,
165+
autosize=True,
166+
width=600,
167+
height=400,
168+
margin=dict(t=40, b=40, l=80, r=40), # noqa: E741
169+
hovermode='closest',
170+
bargap=0,
171+
xaxis=x_layout,
172+
yaxis=y_layout,
173+
title=title
174+
)
175+
176+
fig = go.Figure(data=data, layout=layout)
177+
plot_div = plot(fig, output_type='div', include_plotlyjs=False, show_link=False)
178+
if publish:
179+
try:
180+
return publish_plot(instrument, run_number, files={'file': plot_div})
181+
except: # noqa: E722
182+
logging.error("Publish plot failed: %s", sys.exc_value)
183+
return None
184+
else:
185+
return plot_div
186+
187+
188+
def plot_heatmap(run_number, x, y, z, x_title='', y_title='', surface=False,
189+
x_log=False, y_log=False, instrument='', title='', publish=True):
190+
"""
191+
Produce a 2D plot
192+
"""
193+
from plotly.offline import plot
194+
import plotly.graph_objs as go
195+
196+
x_layout = dict(title=x_title, zeroline=False, exponentformat="power",
197+
showexponent="all", showgrid=True,
198+
showline=True, mirror="all", ticks="inside")
199+
if x_log:
200+
x_layout['type'] = 'log'
201+
202+
y_layout = dict(title=y_title, zeroline=False, exponentformat="power",
203+
showexponent="all", showgrid=True,
204+
showline=True, mirror="all", ticks="inside")
205+
if y_log:
206+
y_layout['type'] = 'log'
207+
208+
layout = go.Layout(
209+
showlegend=False,
210+
autosize=True,
211+
width=600,
212+
height=500,
213+
margin=dict(t=40, b=40, l=80, r=40), # noqa: E741
214+
hovermode='closest',
215+
bargap=0,
216+
xaxis=x_layout,
217+
yaxis=y_layout,
218+
title=title
219+
)
220+
221+
colorscale = [[0, "rgb(0,0,131)"], [0.125, "rgb(0,60,170)"], [0.375, "rgb(5,255,255)"],
222+
[0.625, "rgb(255,255,0)"], [0.875, "rgb(250,0,0)"], [1, "rgb(128,0,0)"]]
223+
plot_type = 'surface' if surface else 'heatmap'
224+
trace = go.Heatmap(z=z, x=x, y=y, autocolorscale=False, # type=plot_type,
225+
hoverinfo="none", colorscale=colorscale)
226+
fig = go.Figure(data=[trace], layout=layout)
227+
plot_div = plot(fig, output_type='div', include_plotlyjs=False, show_link=False)
228+
229+
# The following would remove the hover options, which are not accessible through python
230+
# https://github.com/plotly/plotly.js/blob/master/src/components/modebar/buttons.js
231+
# plot_div = plot_div.replace('modeBarButtonsToRemove:[]',
232+
# 'modeBarButtonsToRemove:["hoverClosestCartesian",
233+
# "hoverCompareCartesian"]')
234+
235+
if publish:
236+
try:
237+
return publish_plot(instrument, run_number, files={'file': plot_div})
238+
except: # noqa: E722
239+
logging.error("Publish plot failed: %s", sys.exc_value)
240+
return None
241+
else:
242+
return plot_div
243+
244+
106245
if __name__ == '__main__':
107246
import sys
108247
div = _loadDiv(sys.argv[1])
109-
#print('**********')
110-
#print(div)
111248

112249
# run information is generated from the filename
113-
name = os.path.split(sys.argv[1])[-1]
250+
name = os.path.split(sys.argv[1])[-1]
114251
(instr, runnumber) = name.split('_')[:2]
115252

116253
config = read_configuration('post_processing.conf')
117-
#config = read_configuration('post_processing_full.conf')
118-
request = publish_plot(instr, runnumber, {'file':div}, config)
254+
request = publish_plot(instr, runnumber, {'file': div}, config)
119255
print('request returned', request.status_code)

0 commit comments

Comments
 (0)