- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplotitems.py
More file actions
Latest commit
539 lines (451 loc) · 17.8 KB
/
Copy pathplotitems.py
File metadata and controls
539 lines (451 loc) · 17.8 KB
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# EvilPlot
# Copyright 2008 Brigham Young University
#
# This file is part of EvilPlot.
#
# EvilPlot is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# EvilPlot is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# EvilPlot. If not, see <http://www.gnu.org/licenses/>.
#
# Inquiries regarding any further use of the Materials contained on this site,
# please contact the Copyright Licensing Office, Brigham Young University,
# 3760 HBLL, Provo, UT 84602, (801) 422-9339 or 422-3821, e-mail
# copyright@byu.edu.
"""Individual items that can be plotted."""
from __future__ importdivision
from __future__ importprint_function
fromsix.movesimportxrangeasrange
importsys
from .paramimportParam, ParamObj
from .utilimportlinspace, min_ifexists, max_ifexists
try:
fromitertoolsimportimapasmap
exceptImportError:
pass
classPlotItem(ParamObj):
"""
This is a basic PlotItem class that needs to be extended to be useful.
"""
_params=dict(filename=Param(default='', doc="Where to write data; '' is automatic"),
dim=Param(doc="Dimensionality; either 2 or 3"),
title=Param(doc='Title in the key for this PlotItem'),
xmin=Param(doc='Minimum x value'),
xmax=Param(doc='Maximum x value'),
ymin=Param(doc='Minimum y value, if 3D'),
ymax=Param(doc='Maximum y value, if 3D'),
style=Param(doc='Gnuplot plotting style', default='points'),
smooth=Param(doc='Smoothing style'),
linewidth=Param(default=4, doc="Width of lines"),
pointsize=Param(default=1.5, doc="Size of points"),
pointtype=Param(doc="Type of points"),
)
def__init__(self, **kwds):
ParamObj.__init__(self, **kwds)
self.external_datafile=False
defgpi_command(self, dim):
"""Return the gnuplot command to plot this PlotItem."""
s="'%s'"% (self.filenameifself.filenameelse'-')
try:
s+=' '+self.using
exceptAttributeError:
pass
ifdim==2andself.smooth:
s+=' smooth %s'%self.smooth
ifself.title:
s+=' title "%s"'%self.title
else:
s+=' notitle'
s+=' with %s'%self.style
ifself.stylein ('lines', 'linespoints', 'errorbars'):
s+=' lw %s'%self.linewidth
ifself.stylein ('linespoints', 'points', 'errorbars'):
s+=' ps %s'%self.pointsize
ifself.pointtype:
s+=' pt %s'%self.pointtype
returns
defpgf_command(self, dim, filename, opts=None, indices=None):
"""Return the PGF command to plot this PlotItem.
Note that only a subset of options are currently supported.
"""
assertdim==2, 'Only 2D currently supported in PGF mode'
lines= []
s="'%s'"% (self.filenameifself.filenameelse'-')
ifnotopts:
opts= []
ifself.smooth:
opts.append('smooth')
ifself.style=='lines':
opts.append('mark=none')
ifnotindices:
indices= ['x index=0', 'y index=1']
opts=','.join(opts)
indices=','.join(indices)
line=r'\addplot +[%s] table[%s] {%s};'% (opts, indices, filename)
lines.append(line)
# Legend
ifself.title:
legend=r'\small %s'%self.title
#legend = r'\footnotesize %s' % self.title
#legend = self.title
lines.append(r'\addlegendentry{%s}'%legend)
return'\n'.join(lines)
defsamples(self, dim, domain):
"""Return a list of sample points for a given domain min/max.
xmin, xmax, ymin, ymax = domain
If the plot should be 2D, then ymin and ymax are None.
"""
return []
defdata(self, dim, domain):
"""Return all of the data as a string.
"""
datalines= []
forvaluesinself.samples(dim, domain):
ifvaluesisnotNone:
line=' '.join(map(str, values))
else:
line=''
datalines.append(line)
return'\n'.join(datalines)
defwrite(self, dim, domain, filename=None):
"""Write out the data to a file.
Open up a file (or stdout if no filename is specified) and write
out the data to a file.
"""
iffilename:
out=open(filename, 'w')
else:
out=sys.stdout
try:
forvaluesinself.samples(dim, domain):
ifvaluesisnotNone:
print(' '.join(map(str, values)), file=out)
finally:
iffilename:
out.close()
classFunction(PlotItem):
"""
This is a PlotItem that can be passed to a plot object. It takes a
continuous function on a real-valued interval, which it will sample from.
f = function(thefunction, xmin=-1.0, xmax=1.0)
Note that you probably want style='pm3d' if you have a 3D function.
TODO: Discontinuities (add a blank line in samples)
"""
_params=dict(style=Param(default='lines'),
resolution=Param(doc='Number of samples in each dim', default=100),
smooth=Param(default='csplines'),
)
def__init__(self, func, **kwds):
super(Function, self).__init__(**kwds)
self.f=func
# Find out the dimensionality of the function.
ifhasattr(func, 'dimensions') andhasattr(func, 'constraints'):
# Chris-style function
self.pass_as_tuple=True
self.dim=func.dimensions+1
self.xmin, self.xmax=func.constraints[0]
ifself.dim==3:
self.ymin, self.ymax=func.constraints[1]
else:
self.pass_as_tuple=False
importinspect
try:
args=inspect.getargspec(self.f)[0]
im_self=getattr(self.f, 'im_self', None)
ifim_selfisNone:
argcount=len(args)
else:
argcount=len(args) -1
exceptTypeError:
try:
args=inspect.getargspec(self.f.__call__)[0]
argcount=len(args) -1
exceptTypeError:
raiseTypeError('Function PlotItem was given a non-function arg.')
self.dim=argcount+1
ifself.dimnotin (2, 3):
raiseTypeError('Wrong dimensionality. Function must be f(x) or f(x,y)')
defsamples(self, dim, domain):
# Note that self.dim is a property of the function and dim is a
# property of the plot.
xmin=max_ifexists(domain[0], self.xmin)
xmax=min_ifexists(domain[1], self.xmax)
ymin=max_ifexists(domain[2], self.ymin)
ymax=min_ifexists(domain[3], self.ymax)
data= []
# Gnuplot requires that we loop through y before x.
ifdim==2:
forxinlinspace(xmin, xmax, self.resolution):
ifself.pass_as_tuple:
sample=x, self.f((x))
else:
sample=x, self.f(x)
data.append(sample)
elifdim==3:
foryinlinspace(ymin, ymax, self.resolution):
forxinlinspace(xmin, xmax, self.resolution):
ifself.dim==2:
ifself.pass_as_tuple:
sample=x, y, self.f((x))
else:
sample=x, y, self.f(x)
else:
ifself.pass_as_tuple:
sample=x, y, self.f((x, y))
else:
sample=x, y, self.f(x, y)
data.append(sample)
data.append(None)
returndata
classHistogram(PlotItem):
"""
Histogram is a PlotItem that can be added to a plot object. It takes a
list of real-valued samples and adds them to a specified number of
buckets. Note that the plot should probably have ymin=0, or else the
scaling will look wrong.
h = histogram(samples, nbuckets)
"""
_params=dict(
style=Param(default='boxes'),
normalize=Param(default=False, doc="Normalize (as probabilities)"),
)
def__init__(self, samples, nbuckets, **kwds):
super(Histogram, self).__init__(**kwds)
self.datalist=samples
self.nbuckets=nbuckets
self.xmin=min(samples)
self.xmax=max(samples)
defsamples(self, dim, domain):
assert(dim==2)
xmin=domain[0]
xmax=domain[1]
width= (xmax-xmin) /float(self.nbuckets)
buckets= [0foriinrange(self.nbuckets)]
forxinself.datalist:
ifx>=xminandx<=xmax:
i=int((x-xmin)/width)
# borderline case that shouldn't make much of a difference
# (only happens when x==max):
ifi==self.nbuckets:
i-=1
buckets[i] +=1
ifself.normalize:
scale=1/ (width*len(self.datalist))
else:
scale=1
minbucketcenter=xmin+width/2
return [(minbucketcenter+i*width, buckets[i] *scale, width) \
foriinrange(self.nbuckets)]
classDensity(PlotItem):
"""
Density is a PlotItem that can be added to a plot object. It takes a list
of real-valued samples from a probability distribution and smooths them to
make a pretty pdf. Note that this "hides the warts," so in many
situations it may be ideal to plot the density on top of the histogram.
d = density(samples)
"""
_params=dict(
bandwidth=Param(doc='Relative KDE Bandwidth: 1 is for xmax-xmin', default=1/17),
smooth=Param(default='csplines'),
style=Param(default='lines'),
resolution=Param(doc='Number of samples in plot', default=100),
)
def__init__(self, draws, **kwds):
super(Density, self).__init__(**kwds)
try:
importnumpy
self.draws=numpy.array(draws)
except:
importNumeric
self.draws=Numeric.array(draws)
if'xmin'notinkwds:
self.xmin=min(draws)
if'xmax'notinkwds:
self.xmax=max(draws)
defsamples(self, dim, domain):
assert(dim==2)
xmin=domain[0]
xmax=domain[1]
fromscipy.stats.kdeimportgaussian_kde
xvalues=list(linspace(xmin, xmax, self.resolution))
pdf=gaussian_kde(self.draws)
yvalues=pdf(xvalues)
returnlist(zip(xvalues, yvalues))
classPoints(PlotItem):
"""
Just print some simple points. Give me a list of tuples.
"""
def__init__(self, pointlist, **kwds):
super(Points, self).__init__(**kwds)
self.pointlist=pointlist
self.dim=len(pointlist[0])
assert(self.dim==2orself.dim==3)
if'xmin'notinkwds:
self.xmin=min(x[0] forxinself.pointlist)
if'xmax'notinkwds:
self.xmax=max(x[0] forxinself.pointlist)
ifself.dim==3:
if'ymin'notinkwds:
self.ymin=min(x[1] forxinself.pointlist)
if'ymax'notinkwds:
self.ymax=max(x[1] forxinself.pointlist)
defsamples(self, dim, domain):
xmin, xmax, ymin, ymax=domain
assert(dim==self.dim)
l= []
ifdim==2:
forxinself.pointlist:
ifx[0] >=xminandx[0] <=xmax:
l.append(x)
elifdim==3:
forxinself.pointlist:
ifx[0] >=xminandx[0] <=xmaxandx[1] >=yminandx[1] <=ymax:
l.append(x)
returnl
classRawData(PlotItem):
"""A plot item for arbitrary 2D data.
RawData is especially useful for specialized styles such as errorbars or
candlesticks.
Not that error bars should be plotted _before_ the associated plot to
ensure that the same colors get used in PGFPlots.
"""
def__init__(self, pointlist, **kwds):
super(RawData, self).__init__(**kwds)
self.pointlist=pointlist
if'xmin'notinkwds:
self.xmin=min(x[0] forxinself.pointlist)
if'xmax'notinkwds:
self.xmax=max(x[0] forxinself.pointlist)
defsamples(self, dim, domain):
xmin, xmax, ymin, ymax=domain
return [xforxinself.pointlistif (x[0] >=xminandx[0] <=xmax)]
defpgf_command(self, dim, filename):
opts= ['forget plot', 'mark=none', 'error bars/.cd', 'y explicit']
indices= ['x index=0', 'y index=1']
plus_opts=opts+ ['y dir=plus']
plus_indices=indices+ [r'y error expr=\thisrowno{3}-\thisrowno{1}']
plus_str=super(RawData, self).pgf_command(dim, filename, plus_opts,
plus_indices)
minus_opts=opts+ ['y dir=minus']
minus_indices=indices+ [r'y error expr=\thisrowno{1}-\thisrowno{2}']
minus_str=super(RawData, self).pgf_command(dim, filename, minus_opts,
minus_indices)
return'%s\n%s'% (plus_str, minus_str)
classVectors(PlotItem):
"""Plots a set of vectors based on (x1, y1, x2, y2) tuples.
If endpoints is specified, x2 and y2 indicate the tip of the arrow.
Otherwise, x2 and y2 indicate the delta.
todo: look more at "set clip" and at "arrowstyle"
"""
_params=dict(
heads=Param(doc='Number of heads (0, 1, or 2)', default=1),
endpoints=Param(doc='Specify endpoints instead of start and delta',
default=False),
style=Param(default='vectors')
)
def__init__(self, pointlist, **kwds):
super(Vectors, self).__init__(**kwds)
self.pointlist=pointlist
self.dim=2
if'xmin'notinkwds:
ifself.endpoints:
fromitertoolsimportchain
self.xmin=min(chain(
(x[0] forxinself.pointlist),
(x[2] forxinself.pointlist)))
else:
self.xmin=min(x[0] forxinself.pointlist)
if'xmax'notinkwds:
ifself.endpoints:
fromitertoolsimportchain
self.xmax=max(chain(
(x[0] forxinself.pointlist),
(x[2] forxinself.pointlist)))
else:
self.xmax=max(x[0] forxinself.pointlist)
defgpi_command(self, dim):
s=super(Vectors, self).gpi_command(dim)
ifself.heads==0:
s+=' nohead'
elifself.heads==1:
s+=' head'
else:
s+=' heads'
returns
defsamples(self, dim, domain):
# right now we don't do any clipping (we ignore domain)
assert(dim==self.dim)
ifself.endpoints:
return [(x1, y1, x2-x1, y2-y1) forx1, y1, x2, y2inself.pointlist]
else:
returnself.pointlist
classExternal(PlotItem):
"""A PlotItem for plotting data from an external data file.
Right now we assume that dims = 2
"""
_params=dict(
fields=Param(default=None,
doc='Which fields of the file to use (using). note: 1-indexed')
)
def__init__(self, filename, **kwds):
super(External, self).__init__(**kwds)
self.dims=2
self.external_datafile=True
self.filename=filename
self.reload()
defget_using(self):
ifself.fieldsisnotNone:
return'using %s'%':'.join(str(f) forfinself.fields)
else:
return''
using=property(fget=get_using)
defreload(self):
"""We should parse the file and calculate dims, xmin, xmax,
ymin, ymax, etc. Be careful about:
- quoted strings, which are a single field, even if there
are spaces inside them (currently ignored)
- Gnuplot will assume that the data have 2 dimensions, even if
there is just one field.
"""
ifself.fieldsisNone:
xfield=0
yfield=1
else:
xfield=self.fields[0] -1
yfield=self.fields[1] -1
xmin=xmax=None
ymin=ymax=None
forlineinopen(self.filename):
stripped_line=line.strip()
ifstripped_line!=''andstripped_line[0] !='#':
data= [float(x) forxinstripped_line.split()]
ifxminisNone:
xmin=xmax=data[xfield]
ymin=ymax=data[yfield]
else:
xmin=min(data[xfield], xmin)
xmax=max(data[xfield], xmax)
ymin=min(data[yfield], ymin)
ymax=max(data[yfield], ymax)
self.xmin=xmin
self.xmax=xmax
self.ymin=ymin
self.ymax=ymax
########################################################################
### TESTING
if__name__=='__main__':
p=plot(title='x**2', xmin=-4, xmax=4)
p.append(function(lambdax: x**2))
p.show()
p.write(gpifilename='plottest.gpi')
__all__= ['Function', 'Histogram', 'Density', 'Points', 'RawData', 'Vectors',
'External']
# vim: et sw=4 sts=4