forked from argriffing/xgcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
20100804b.py
265 lines (246 loc) · 9.85 KB
/
20100804b.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
"""
Scatter plot 2D given an R table with one categorical and one numerical var.
"""
from StringIO import StringIO
import os
import argparse
from SnippetUtil import HandlingError
import Form
import FormOut
import Util
import Carbone
import RUtil
import iterutils
import const
g_tags = ['pca:plot']
g_default = const.read('20100709a')
#FIXME multiple output types
class MissingError(Exception): pass
def get_form():
"""
@return: the body of a form
"""
form_objects = [
Form.MultiLine('table', 'R table', g_default),
Form.Sequence('axes',
'numerical variables defining axes of the plot',
('pc1', 'pc2')),
Form.SingleLine('shape',
'categorical variable defining the shape of a dot',
'species'),
Form.SingleLine('color',
'numerical variable defining the color of a dot',
'temperature'),
Form.Float('size', 'size of a plotted point', '1.5'),
Form.Sequence('legend_pos', 'position of the symbol legend',
('0', '-1')),
Form.CheckGroup('pixel_options', 'more plotting details', [
Form.CheckItem('endpoint_ticks',
'add ticks to the endpoints of the colorbar', True)]),
Form.ImageFormat()]
#Form.RadioGroup('out_type', 'output type', [
#Form.RadioItem('show_image', 'image', True),
#Form.RadioItem('show_table', 'R table'),
#Form.RadioItem('show_script', 'R script')]),
return form_objects
def get_form_out():
return FormOut.Image('%s.%s.pca.3d', ['shape', 'color'])
def get_response_content(fs):
# create a response that depends on the requested output type
#if fs.show_image:
if 1:
content = process(fs, fs.table.splitlines())
#ext = Form.g_imageformat_to_ext[fs.imageformat]
#filename = '.'.join((fs.shape, fs.color, 'pca', '2d', ext))
#contenttype = Form.g_imageformat_to_contenttype[fs.imageformat]
"""
else:
# read the table
rtable = RUtil.RTable(fs.table.splitlines())
header_row = rtable.headers
data_rows = rtable.data
# Do a more stringent check of the column headers.
for h in header_row:
if not Carbone.is_valid_header(h):
msg = 'invalid column header: %s' % h
raise ValueError(msg)
plot_info = PlotInfo(fs, header_row, data_rows)
if fs.show_table:
content = '\n'.join(plot_info.get_augmented_table_lines()) + '\n'
contenttype = 'text/plain'
filename = 'out.table'
elif fs.show_script:
stub_image_name = 'stub-image-filename.' + fs.imageformat
stub_table_name = 'stub-table-filename.table'
content = plot_info.get_script(
fs, stub_image_name, stub_table_name) + '\n'
contenttype = 'text/plain'
filename = 'script.R'
"""
return content
class PlotInfo:
def __init__(self, args, headers, data):
"""
@param args: user args from web or cmdline
@param data:
"""
# map the column header to the column index
self.h_to_i = dict((h, i+1) for i, h in enumerate(headers))
# init the info
self._init_axes(args, headers, data)
self._init_colors(args, headers, data)
self._init_shapes(args, headers, data)
self._init_unique_shapes()
def _init_axes(self, args, headers, data):
# read the axes
self.axis_headers = args.axes
# verify the number of axis headers
if len(self.axis_headers) != 2:
raise ValueError('expected two axis column headers')
# verify the axis header contents
bad_axis_headers = set(self.axis_headers) - set(headers)
if bad_axis_headers:
raise ValueError(
'bad axis column headers: ' + ', '.join(bad_axis_headers))
self.axis_lists = []
for h in self.axis_headers:
index = self.h_to_i[h]
try:
axis_list = Carbone.get_numeric_column(data, index)
except Carbone.NumericError:
raise ValueError(
'expected the axis column %s '
'to be numeric' % h)
self.axis_lists.append(axis_list)
def _init_colors(self, args, headers, data):
"""
Colors are numeric, and use whatever gradient is built into R.
"""
self.color_header = args.color
if self.color_header not in headers:
raise ValueError('bad color column header: ' + self.color_header)
index = self.h_to_i[self.color_header]
try:
self.color_list = Carbone.get_numeric_column(data, index)
except Carbone.NumericError:
raise ValueError(
'expected the color column %s '
'to be numeric' % self.color_header)
def _init_shapes(self, args, headers, data):
"""
Shapes are categorical.
"""
self.shape_header = args.shape
if self.shape_header not in headers:
raise ValueError('bad shape column header: ' + self.shape_header)
index = self.h_to_i[self.shape_header]
self.shape_list = zip(*data)[index]
def _init_unique_shapes(self):
self.unique_shapes = list(iterutils.unique_everseen(self.shape_list))
def get_augmented_table_lines(self):
"""
This is given to R.
"""
nrows = len(self.shape_list)
header_row = ['x', 'y', 'color', 'symbol']
data_rows = zip(
range(1, nrows+1),
self.axis_lists[0],
self.axis_lists[1],
self.color_list,
[self.unique_shapes.index(x) for x in self.shape_list])
header_line = '\t'.join(str(x) for x in header_row)
data_lines = ['\t'.join(str(x) for x in row) for row in data_rows]
return [header_line] + data_lines
def get_script(self, args, temp_plot_filename, temp_table_filename):
"""
@param args: from cmdline or web
@param temp_plot_name: a pathname
@param temp_table_name: a pathname
"""
# get the symbol legend location
try:
legend_pos = Util.get_coordinate_pair(args.legend_pos)
except Util.CoordinatePairError as e:
raise ValueError('legend position error: ' + str(e))
# get the unique locations and species
symbol_legend_string = ', '.join("'%s'" % x for x in self.unique_shapes)
color_legend_string = self.color_header
# add color legend endpoint axis
if args.endpoint_ticks:
s = 'mytable$color'
color_axis = 'axis(1, c(axTicks(1), min(%s), max(%s)))' % (s, s)
else:
color_axis = 'axis(1)'
# get the image function
image_function = Form.g_imageformat_to_r_function[args.imageformat]
rcodes = [
"mytable <- read.table('%s')" % temp_table_filename,
"%s('%s')" % (image_function, temp_plot_filename),
# stack two plots vertically
"layout(cbind(1:2, 1:2), heights = c(7, 1.5))",
# create the color gradient
"prc <- hsv((prc <- 0.7*mytable$color/diff(range(mytable$color))) - min(prc) + 0.3)",
# create the scatterplot
"myplot <- plot(mytable$x, mytable$y, mar = c(5, 3, 4, 3),",
"xlab = '%s'," % self.axis_headers[0],
"ylab = '%s'," % self.axis_headers[1],
"type = 'p', pch = ' ')",
# define symbols colors and sizes
"points(mytable$x, mytable$y,",
"pch=mytable$symbol, bg=prc, col=prc, cex=%s)" % args.size,
# symbol legend
"legend(%s, %s," % legend_pos,
"pch=0:%s, yjust = 0," % (len(symbol_legend_string)-1),
"legend=c(%s)," % symbol_legend_string,
"cex = 1.1)",
# set margins
"par(mar=c(5, 3, 0.5, 3))",
# draw the plot
"plot(seq(min(mytable$color), max(mytable$color), length = 100),",
"rep(0, 100), pch = 15, cex = 2,",
"axes = FALSE,",
"xlab = '%s'," % color_legend_string,
"ylab = '', col = hsv(seq(0.3, 1, length = 100)))",
# draw the axis onto the color legend
color_axis,
# write the plot
"dev.off()"]
return '\n'.join(rcodes)
def process(args, table_lines):
"""
@param args: command line or web input
@param table_lines: input lines
@return: the image data as a string
"""
rtable = RUtil.RTable(table_lines)
header_row = rtable.headers
data_rows = rtable.data
Carbone.validate_headers(header_row)
# Read the relevant columns and their labels.
plot_info = PlotInfo(args, header_row, data_rows)
# Get info for the temporary data
augmented_lines = plot_info.get_augmented_table_lines()
table_string = '\n'.join(augmented_lines)
temp_table_name = Util.create_tmp_file(table_string, suffix='.table')
temp_plot_name = Util.get_tmp_filename()
script = plot_info.get_script(args, temp_plot_name, temp_table_name)
temp_script_name = Util.create_tmp_file(script, suffix='.R')
# Call R.
retcode, r_out, r_err = RUtil.run(temp_script_name)
if retcode:
raise ValueError('R error:\n' + r_err)
# Delete the temporary data table file.
os.unlink(temp_table_name)
# Delete the temporary script file.
os.unlink(temp_script_name)
# Read the image file.
try:
with open(temp_plot_name, 'rb') as fin:
image_data = fin.read()
except IOError as e:
raise HandlingError('the R call seems to not have created the plot')
# Delete the temporary image file.
os.unlink(temp_plot_name)
# Return the image data as a string.
return image_data