-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathplotting.py
790 lines (597 loc) · 23.4 KB
/
plotting.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
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
###############################################################################
# Graph plot class (GNUPLOT wrapper)
import sys, os
from util import *
class Gnuplot:
class Plot:
def __init__(self, xlist, ylist, zlist, options):
self.xlist = copy.copy(xlist)
self.ylist = copy.copy(ylist)
self.zlist = copy.copy(zlist)
self.options = copy.copy(options)
def __init__(self):
self.data = []
self.stream = None
self.margin = .1
self.enable = True
self.options = {
# plot options
"style" : "points",
"main" : "",
"xlab" : "",
"ylab" : "",
"zlab" : "",
"plab" : "",
"eqn": None,
# graph options
"xmin" : None,
"xmax" : None,
"ymin" : None,
"ymax" : None,
"zmax" : None,
"zmin" : None,
"xtics" : None,
"ytics" : None,
"ztics" : None,
"xlog": None,
"ylog": None,
"zlog": None,
"margin": None
}
def set(self, **options):
for key in options:
self.options[key] = options[key]
self.replot()
def gnuplot(self, text):
self.stream.write(text)
def xrange(self, start = None, end = None):
self.options["xmin"] = start
self.options["xmax"] = end
self.replot()
def yrange(self, start = None, end = None):
self.options["ymin"] = start
self.options["ymax"] = end
self.replot()
def zrange(self, start = None, end = None):
self.options["zmin"] = start
self.options["zmax"] = end
self.replot()
def unlog(self):
self.options["xlog"] = False
self.options["ylog"] = False
self.options["zlog"] = False
self.replot()
def xlog(self, base=10):
self.options["xlog"] = base
self.replot()
def ylog(self, base=10):
self.options["ylog"] = base
self.replot()
def zlog(self, base=10):
self.options["zlog"] = base
self.replot()
def loglog(self, base=10):
self.options["xlog"] = base
self.options["ylog"] = base
self.replot()
def clear(self):
self.data = []
def save(self, filename = "", format="x11"):
if not self.enable:
return
if filename == "":
tmpfile = self.setTerminal(filename, format)
self.replot()
# wait until plot appears
self.wait()
text = file(tmpfile).read()
os.remove(tmpfile)
else:
self.setTerminal(filename, format)
self.replot()
text = None
# reset format
#print >>self.stream, "set terminal windows"
return text
def savedata(self, filename):
"""Save gnuplot commands in filename"""
self.stream = file(filename, "w")
self.replot()
self.enableOutput()
def savetab(self, filename):
"""Save data in tab delimited format"""
out = openStream(filename, "w")
for data in self.data:
print data
print >>out, data.options["plab"]
if len(data.ylist) > 0:
if len(data.zlist) > 0:
rows = zip(data.xlist, data.ylist, data.zlist)
labels = mget(data.options, ["xlab", "ylab", "zlab"])
else:
rows = zip(data.xlist, data.ylist)
labels = mget(data.options, ["xlab", "ylab"])
print >>out, "\t".join(labels)
for row in rows:
print >>out, "\t".join(map(str, row))
print >>out
def saveall(self, filename):
"""
Save gnuplot commands, tad delimited, and plot image in the
following files:
<filename>.gnuplot
<filename>.tab
<filename>.png
"""
if not self.enable:
return
self.savedata(filename + ".gnuplot")
self.savetab(filename + ".tab")
self.save(filename + ".png")
def setTerminal(self, filename = "", format="x11"):
if not self.enable:
return
# auto detect format from filename
if filename != "":
print >>self.stream, "set output \"%s\"" % filename
# determine format
if filename.endswith(".ps"):
format = "ps"
if filename.endswith(".pdf"):
format = "pdf"
if filename.endswith(".gif"):
format = "gif"
if filename.endswith(".png"):
format = "png"
if filename.endswith(".jpg"):
format = "jpg"
else:
tmpfile = tempfile(".", "gnuplot", ".ps")
print >>self.stream, "set output \"%s\"" % tmpfile
return tmpfile
# set terminal format
if format == "ps":
print >>self.stream, "set terminal postscript color"
elif format == "pdf":
print >>self.stream, "set terminal pdf"
elif format == "gif":
print >>self.stream, "set terminal gif"
elif format == "jpg":
print >>self.stream, "set terminal jpeg"
else:
print >>self.stream, "set terminal %s" % format
def wait(self):
"""Wait until all commands are known to be excuted"""
tmpfile = tempfile(".", "gnuplot", ".ps")
print >>self.stream, "set output '%s'" % tmpfile
print >>self.stream, "set terminal postscript color"
print >>self.stream, "plot '-'\n0 0\ne\n"
self.stream.flush()
while not os.path.isfile(tmpfile): pass
os.remove(tmpfile)
def findRange(self):
bestLeft = 1e500
bestRight = -1e500
bestTop = -1e500
bestBottom = 1e500
# find ranges for each graph that is plotted
for graph in self.data:
if graph.options["eqn"]:
continue
list1 = graph.xlist
list2 = graph.ylist
# find border
top = max(list2)
bottom = min(list2)
left = min(list1)
right = max(list1)
# find margin
ymargin = (top - bottom) * self.margin
xmargin = (right - left) * self.margin
if xmargin == 0: xmargin = 1
if ymargin == 0: ymargin = 1
# find new border
top += ymargin
bottom -= ymargin
left -= xmargin
right += xmargin
# record biggest range thus far
if top > bestTop: bestTop = top
if bottom < bestBottom: bestBottom = bottom
if left < bestLeft: bestLeft = left
if right > bestRight: bestRight = right
# auto scale
if bestLeft >= .1e500: bestLeft = "*"
if bestRight <= -1e500: bestRight = "*"
if bestTop <= -1e500: bestTop = "*"
if bestBottom >= 1e500: bestBottom = "*"
return (bestTop, bestBottom, bestLeft, bestRight)
def replot(self):
# do nothing if no data or plotting is not enabled
if len(self.data) == 0 or \
not self.enable:
return
# configure
print >>self.stream, "set mouse"
print >>self.stream, "set mxtics"
print >>self.stream, "set mytics"
print >>self.stream, "set mztics"
# margins
if self.options["margin"]:
print >>self.stream, "set tmargin %f" % self.options["margin"]
print >>self.stream, "set bmargin %f" % self.options["margin"]
print >>self.stream, "set lmargin %f" % self.options["margin"]
print >>self.stream, "set rmargin %f" % self.options["margin"]
else:
print >>self.stream, "set tmargin"
print >>self.stream, "set bmargin"
print >>self.stream, "set lmargin"
print >>self.stream, "set rmargin"
# tics
if self.options["xtics"] == None:
print >>self.stream, "set xtics autofreq"
else:
print >>self.stream, "set xtics %f" % self.options["xtics"]
if self.options["ytics"] == None:
print >>self.stream, "set ytics autofreq"
else:
print >>self.stream, "set ytics %f" % self.options["ytics"]
if self.options["ztics"] == None:
print >>self.stream, "set ztics autofreq"
else:
print >>self.stream, "set ztics %f" % self.options["ztics"]
# log scale
print >>self.stream, "unset logscale xyz"
if self.options["xlog"]:
print >>self.stream, "set logscale x %d" % self.options["xlog"]
if self.options["ylog"]:
print >>self.stream, "set logscale y %d" % self.options["ylog"]
if self.options["zlog"]:
print >>self.stream, "set logscale z %d" % self.options["zlog"]
# setup ranges
(maxy, miny, minx, maxx) = self.findRange()
if self.options["xmin"] != None: minx = self.options["xmin"]
if self.options["xmax"] != None: maxx = self.options["xmax"]
if self.options["ymin"] != None: miny = self.options["ymin"]
if self.options["ymax"] != None: maxy = self.options["ymax"]
print >>self.stream, "set xrange[%s:%s]" % tuple(map(str, [minx, maxx]))
print >>self.stream, "set yrange[%s:%s]" % tuple(map(str, [miny, maxy]))
# TODO: add range z
# set labels
if self.options["main"] != "":
print >>self.stream, "set title \"" + self.options["main"] + "\""
if self.options["xlab"] != "":
print >>self.stream, "set xlabel \"" + self.options["xlab"] + "\""
if self.options["ylab"] != "":
print >>self.stream, "set ylabel \"" + self.options["ylab"] + "\""
if self.options["zlab"] != "":
print >>self.stream, "set zlabel \"" + self.options["zlab"] + "\""
# give plot command
if self.data[0].zlist == []:
print >>self.stream, "plot ",
else:
print >>self.stream, "splot ",
for i in range(len(self.data)):
graph = self.data[i]
if graph.options["eqn"]:
# specify direct equation
print >>self.stream, graph.options["eqn"],
else:
# specify inline data
print >>self.stream, "\"-\" ",
# specify style
if graph.options["style"] != "":
print >>self.stream, "with ", graph.options["style"],
# specify plot label
if graph.options["plab"] != "":
print >>self.stream, " title \""+ graph.options["plab"] +"\"",
else:
print >>self.stream, " notitle",
if i < len(self.data) - 1:
print >>self.stream, ",",
print >>self.stream, ""
# output data
for graph in self.data:
if graph.options["eqn"]:
continue
self.outputData(graph.xlist, graph.ylist, graph.zlist, graph.options)
# need to make sure gnuplot gets what we have written
self.stream.flush()
self.stream.close()
os.system("gnuplot tmpplot.gp")
self.stream = file("tmpplot.gp", "w")
def prepareData(self, list1, list2=[], list3=[]):
if list2 == []:
list2 = list1
list1 = range(len(list1))
if len(list1) != len(list2):
raise Exception("ERROR: arrays are not same length")
return list1, list2, list3
def outputData(self, list1, list2, list3=[], options={}):
for i in range(len(list1)):
if list3 == []:
print >>self.stream, list1[i], \
list2[i],
else:
print >>self.stream, list1[i], \
list2[i], \
list3[i],
# error bars
if "err" in options:
print >>self.stream, options["err"][i],
if "errlow" in options and "errhi" in options:
print >>self.stream, options["errlow"][i], options["errhi"][i],
# newline
print >>self.stream
print >>self.stream, "e"
def plot(self, list1, list2=[], list3=[], **options):
self.set(**options)
list1, list2, list3 = self.prepareData(list1, list2, list3)
self.data.append(self.Plot(list1, list2, list3, copy.copy(self.options)))
if self.enable:
self.stream = file("tmpplot.gp", "w") #os.popen("gnuplot", "w")
self.replot()
def gfit(self, func, eqn, params, list1, list2=[], list3=[], ** options):
"""
all syntax should be valid GNUPLOT syntax
func - a string of the function call i.e. "f(x)"
eqn - a string of a GNUPLOT equation "a*x**b"
params - a dictionary of parameters in eqn and their initial values
ex: {"a": 1, "b": 3}
"""
self.set(** options)
print len(list1), len(list2), len(list3)
if not self.enable:
raise Exception("must be output must be enabled for fitting")
list1, list2, list3 = self.prepareData(list1, list2, list3)
# add data to graph
self.data.append(self.Plot(list1, list2, list3, copy.copy(self.options)))
# perform fitting
self.stream = os.popen("gnuplot", "w")
print >>self.stream, "%s = %s" % (func, eqn)
for param, value in params.items():
print >>self.stream, "%s = %f" % (param, value)
print >>self.stream, "fit %s '-' via %s" % \
(func, ",".join(params.keys()))
self.outputData(list1, list2, list3)
# save and read parameters
outfile = tempfile(".", "plot", ".txt")
print >>self.stream, "save var '%s'" % outfile
print >>self.stream, "print 'done'"
self.stream.flush()
# wait for variable file
while not os.path.isfile(outfile): pass
params = self.readParams(outfile)
os.remove(outfile)
# build eqn for plotting
paramlist = ""
for param, value in params.items():
paramlist += "%s = %s, " % (param, value)
self.options["eqn"] = paramlist + "%s = %s, %s" % \
(func, eqn, func)
self.options["style"] = "lines"
# add fitted eqn to graph
self.data.append(self.Plot([], [], [], copy.copy(self.options)))
self.replot()
def readParams(self, filename):
params = {}
for line in file(filename):
if line[0] == "#":
continue
var, value = line.split("=")
if not var.startswith("MOUSE_"):
params[var.replace(" ", "")] = float(value)
return params
def plotfunc(self, func, start, end, step, **options):
x = []
y = []
while start < end:
try:
y.append(func(start))
x.append(start)
except ZeroDivisionError:
pass
start += step
self.plot(x, y, style="lines", ** options)
def enableOutput(self, enable = True):
self.enable = enable
if enable:
self.stream = file("tmpplot.gp", "w")#os.popen("gnuplot", "w")
def plot(list1, list2=[], list3=[], **options):
g = options.setdefault("plot", Gnuplot())
g.plot(list1, list2, list3, **options)
return g
def plotfunc(func, start, end, step, **options):
g = options.setdefault("plot", Gnuplot())
g.plotfunc(func, start, end, step, ** options)
return g
def gfit(func, eqn, params, list1, list2=[], list3=[], ** options):
g = options.setdefault("plot", Gnuplot())
g.gfit(func, eqn, params, list1, list2, list3, ** options)
return g
class MultiPlot (Gnuplot):
def __init__(self, plots, ncols=None, nrows=None, direction="row",
width=800, height=800):
Gnuplot.__init__(self)
self.plots = plots
self.stream = os.popen("gnuplot -geometry %dx%d" % (width, height), "w")
self.nrows = nrows
self.ncols = ncols
self.direction = direction
self.replot()
def replot(self):
# determine layout
nplots = len(self.plots)
if self.nrows == None and self.ncols == None:
self.ncols = int(math.sqrt(nplots))
if self.ncols != None:
self.nrows = int(math.ceil(nplots / float(self.ncols)))
else:
self.ncols = int(math.ceil(nplots / float(self.nrows)))
xstep = 1.0 / self.ncols
ystep = 1.0 / self.nrows
ypos = 0
xpos = 0
xorigin = 0.0
yorigin = 1.0
print >>self.stream, "set origin 0, 0"
print >>self.stream, "set size 1, 1"
print >>self.stream, "set multiplot"
for plot in self.plots:
xpt = xorigin + xpos * xstep
ypt = yorigin - (ypos+1) * ystep
print >>self.stream, "set origin %f, %f" % (xpt, ypt)
print >>self.stream, "set size %f, %f" % (xstep, ystep)
plot.stream = self.stream
plot.replot()
if self.direction == "row":
xpos += 1
elif self.direction == "col":
ypos += 1
else:
raise Exception("unknown direction '%s'" % self.direction)
if xpos >= self.ncols:
xpos = 0
ypos += 1
if ypos >= self.nrows:
ypos = 0
xpos += 1
print >>self.stream, "unset multiplot"
# common colors
red = ( 1, 0, 0, 1)
orange = ( 1, .5, 0, 1)
yellow = ( 1, 1, 0, 1)
green = ( 0, 1, 0, 1)
blue = ( 0, 0, 1, 1)
purple = ( 1, 0, 1, 1)
black = ( 0, 0, 0, 1)
grey = (.5, .5, .5, 1)
white = ( 1, 1, 1, 1)
class ColorMap:
def __init__(self, table=[]):
self.table = table
self.table.sort(lambda a,b: cmp(a[0], b[0]))
def get(self, value):
for i in xrange(len(self.table)):
if value <= self.table[i][0]:
break
if i > 0:
i -= 1
if value <= self.table[i][0]:
return self.table[i][1]
elif value >= self.table[i+1][0]:
return self.table[i+1][1]
else:
# blend two nearest colors
part = value - self.table[i][0]
tot = float(self.table[i+1][0] - self.table[i][0])
return vadd(vmuls(self.table[i][1], (tot-part)/tot),
vmuls(self.table[i+1][1], part/tot))
def rainbowColorMap(data=None, low=None, high=None):
if data != None:
low = min(data)
high = max(data)
assert low != None and high != None
return ColorMap([[low, blue],
[.5*low+.5*high, green],
[.25*low + .75*high, yellow],
[high, red]])
def plothist2(x, y, ndivs1=20, ndivs2=20, width=500, height=500):
l, h = hist2(x, y, ndivs1, ndivs2)
bwidth = bucketSize(x)
bheight = bucketSize(y)
#width *= bwidth/bheight
heatmap(h, width/ndivs1, height/ndivs2)
def heatmap(matrix, width=20, height=20, colormap=None, filename=None,
rlabels=None, clabels=None, display=True,
xdir=1, ydir=1,
xmargin=0, ymargin=0,
labelPadding=2,
labelSpacing=4,
showVals=False,
valColor=black):
# determine filename
if filename == None:
filename = tempfile(".", "heatmap", ".svg")
temp = True
else:
temp = False
# determine colormap
if colormap == None:
colormap = rainbowColorMap(flatten(matrix))
# determine matrix size and orientation
nrows = len(matrix)
ncols = len(matrix[0])
if xdir == 1:
xstart = xmargin
ranchor = "end"
coffset = width
elif xdir == -1:
xstart = xmargin + ncols * width
ranchor = "start"
coffset = 0
else:
raise Exception("xdir must be 1 or -1")
if ydir == 1:
ystart = ymargin
roffset = height
canchor = "start"
elif ydir == -1:
ystart = ymargin + nrows * width
roffset = 0
canchor = "end"
else:
raise Exception("ydir must be 1 or -1")
# begin svg
infile = openStream(filename, "w")
s = svg.Svg(infile)
s.beginSvg(ncols*width + 2*xmargin, nrows*height + 2*ymargin)
# draw matrix
for i in xrange(nrows):
for j in xrange(ncols):
color = colormap.get(matrix[i][j])
s.rect(xstart + xdir*j*width,
ystart + ydir*i*height,
xdir*width, ydir*height, color, color)
# draw values
if showVals:
# find text size
textsize = []
for i in xrange(nrows):
for j in xrange(ncols):
strval = "%.2f" % matrix[i][j]
textsize.append(min(height, width/float(len(strval))))
textsize = min(textsize)
for i in xrange(nrows):
for j in xrange(ncols):
strval = "%.2f" % matrix[i][j]
s.text(strval,
xstart + xdir*j*width,
ystart + ydir*i*height +
height/2.0 + textsize/2.0,
textsize,
fillColor=valColor)
# draw labels
if rlabels != None:
assert len(rlabels) == nrows, \
"number of row labels does not equal number of rows"
for i in xrange(nrows):
x = xstart - xdir*labelPadding
y = ystart + roffset + ydir*i*height - labelSpacing/2.
s.text(rlabels[i], x, y, height-labelSpacing, anchor=ranchor)
if clabels != None:
assert len(clabels) == ncols, \
"number of col labels does not equal number of cols"
for j in xrange(ncols):
x = xstart + coffset + xdir*j*width - labelSpacing/2.
y = ystart - ydir*labelPadding
s.text(clabels[j], x, y, width-labelSpacing, anchor=canchor, angle=270)
# end svg
s.endSvg()
s.close()
# display matrix
if display:
os.system("display %s" % filename)
# clean up temp files
if temp:
os.remove(filename)