-
Notifications
You must be signed in to change notification settings - Fork 2
/
plot2
executable file
·277 lines (228 loc) · 9.04 KB
/
plot2
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os,sys,argparse,fileinput,pyqtgraph as pg,numpy as np, matplotlib as mp
from time import time
from pyqtgraph.Qt import QtCore, QtGui
from pyqtgraph.widgets.RemoteGraphicsView import RemoteGraphicsView
from threading import Thread, Event
from collections import deque
import pyqtgraph.examples
pyqtgraph.examples.run()
from math import pi
import numpy as np
def cmap(start=0.5, rot=-1.5, gamma=1.0, reverse=False, nlev=256.,
minSat=1.2, maxSat=1.2, minLight=0., maxLight=1.,
**kwargs):
"""
A full implementation of Dave Green's "cubehelix" for Matplotlib.
Based on the FORTRAN 77 code provided in
D.A. Green, 2011, BASI, 39, 289.
http://adsabs.harvard.edu/abs/2011arXiv1108.5083G
User can adjust all parameters of the cubehelix algorithm.
This enables much greater flexibility in choosing color maps, while
always ensuring the color map scales in intensity from black
to white. A few simple examples:
Default color map settings produce the standard "cubehelix".
Create color map in only blues by setting rot=0 and start=0.
Create reverse (white to black) backwards through the rainbow once
by setting rot=1 and reverse=True.
Parameters
----------
start : scalar, optional
Sets the starting position in the color space. 0=blue, 1=red,
2=green. Defaults to 0.5.
rot : scalar, optional
The number of rotations through the rainbow. Can be positive
or negative, indicating direction of rainbow. Negative values
correspond to Blue->Red direction. Defaults to -1.5
gamma : scalar, optional
The gamma correction for intensity. Defaults to 1.0
reverse : boolean, optional
Set to True to reverse the color map. Will go from black to
white. Good for density plots where shade~density. Defaults to False
nlev : scalar, optional
Defines the number of discrete levels to render colors at.
Defaults to 256.
sat : scalar, optional
The saturation intensity factor. Defaults to 1.2
NOTE: this was formerly known as "hue" parameter
minSat : scalar, optional
Sets the minimum-level saturation. Defaults to 1.2
maxSat : scalar, optional
Sets the maximum-level saturation. Defaults to 1.2
startHue : scalar, optional
Sets the starting color, ranging from [0, 360], as in
D3 version by @mbostock
NOTE: overrides values in start parameter
endHue : scalar, optional
Sets the ending color, ranging from [0, 360], as in
D3 version by @mbostock
NOTE: overrides values in rot parameter
minLight : scalar, optional
Sets the minimum lightness value. Defaults to 0.
maxLight : scalar, optional
Sets the maximum lightness value. Defaults to 1.
Returns
-------
matplotlib.colors.LinearSegmentedColormap object
Example
-------
>>> import cubehelix
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> x = np.random.randn(1000)
>>> y = np.random.randn(1000)
>>> cx = cubehelix.cmap(start=0., rot=-0.5)
>>> plt.hexbin(x, y, gridsize=50, cmap=cx)
Revisions
---------
2014-04 (@jradavenport) Ported from IDL version
2014-04 (@jradavenport) Added kwargs to enable similar to D3 version,
changed name of "hue" parameter to "sat"
"""
# override start and rot if startHue and endHue are set
if kwargs is not None:
if 'startHue' in kwargs:
start = (kwargs.get('startHue') / 360. - 1.) * 3.
if 'endHue' in kwargs:
rot = kwargs.get('endHue') / 360. - start / 3. - 1.
if 'sat' in kwargs:
minSat = kwargs.get('sat')
maxSat = kwargs.get('sat')
# set up the parameters
fract = np.linspace(minLight, maxLight, nlev)
angle = 2.0 * pi * (start / 3.0 + rot * fract + 1.)
fract = fract**gamma
satar = np.linspace(minSat, maxSat, nlev)
amp = satar * fract * (1. - fract) / 2.
# compute the RGB vectors according to main equations
red = fract + amp * (-0.14861 * np.cos(angle) + 1.78277 * np.sin(angle))
grn = fract + amp * (-0.29227 * np.cos(angle) - 0.90649 * np.sin(angle))
blu = fract + amp * (1.97294 * np.cos(angle))
# find where RBB are outside the range [0,1], clip
red[np.where((red > 1.))] = 1.
grn[np.where((grn > 1.))] = 1.
blu[np.where((blu > 1.))] = 1.
red[np.where((red < 0.))] = 0.
grn[np.where((grn < 0.))] = 0.
blu[np.where((blu < 0.))] = 0.
# optional color reverse
if reverse is True:
red = red[::-1]
blu = blu[::-1]
grn = grn[::-1]
# put in to tuple & dictionary structures needed
col = []
for k in range(0, int(nlev)):
col.append((float(k) / (nlev - 1.), red[k], red[k]))
col.append((float(k) / (nlev - 1.), blu[k], blu[k]))
col.append((float(k) / (nlev - 1.), grn[k], grn[k]))
#cdict = {'red': rr, 'blue': bb, 'green': gg}
return [[a*255,b*255,c*255] for (a,b,c) in col]
class MyColorMap():
def __init__(self, maxval, cm=cmap(reverse=True)):
self.m = maxval
self.cm = cm
def __call__(self, val, alpha=255):
i = (len(self.cm)-1) * val/self.m
c = self.cm[int(i)] + [alpha]
return c
class LabelRegion():
def __init__(self,beg,end,label):
self.b = beg
self.e = end
self.l = label
self.r = None
def __repr__(self):
return "%d - %d %s"%(self.b,self.e,self.l)
class InputThread(Thread):
def __init__(self, f,limit=None,quiet=False):
Thread.__init__(self)
self.maxlen = limit
self.pause = Event()
self.pause.set()
self.quiet = quiet
self.f = f
line = f.readline()
if not self.quiet: print(line)
l,*d = line.split()
self.labels = deque(maxlen=limit)
self.labels.append(LabelRegion(0,1,l))
self.data = []
for x in d:
b = deque(maxlen=limit)
self.data.append(b)
b.append(float(x))
self.consumed = 1
def run(self):
for line in self.f:
self.pause.wait()
if not self.quiet: print(line)
label,*data = line.split()
data = [float(x) for x in data]
for q,d in zip(self.data,data):
q.append(d)
lr = self.labels[-1]
if label == lr.l:
lr.e = self.consumed+1
else:
lr = LabelRegion(self.consumed,self.consumed+1,label)
self.labels.append(lr)
if self.maxlen and self.labels[0].e < self.consumed - self.maxlen:
self.labels.popleft()
self.consumed += 1
class LinePlot():
def __init__(self, data,canvas,limit=0):
self.canvas = canvas
self.limit = limit
self.data = data
self.curves = []
cm = MyColorMap(len(data.data))
for i in range(len(data.data)):
p = self.canvas.plot(pen=cm(i), fillBrush=cm(i))
self.curves.append(p)
r = pg.LinearRegionItem(movable=False)
r.setRegion((0,-1))
self.canvas.addItem(r,ignoreBounds=True)
def __call__(self):
for (p,d) in zip(self.curves,self.data.data):
p.setData(d, fillLevel=.3)
if self.limit:
p.setPos(self.data.consumed-self.limit,0)
# get a copy to work on
for lr in self.data.labels:
if lr.l == 'NULL':
continue
if lr.r is None:
lr.r = pg.LinearRegionItem(movable=False)
self.canvas.addItem(lr.r,ignoreBounds=True)
lr.r.setRegion((lr.b,lr.e))
if __name__=="__main__":
cmdline = argparse.ArgumentParser('real-time of data for grt')
cmdline.add_argument('--num-samples', '-n', type=int, default=None, help="plot the last n samples, 0 keeps all")
cmdline.add_argument('--title', '-t', type=str, default="grtool plot", help="plot window title")
cmdline.add_argument('--quiet', '-q', action="store_true", help="if given does not copy input to stdout")
cmdline.add_argument('file', type=str, nargs='?', default='-', help="input files or - for stdin")
args = cmdline.parse_args()
pg.setConfigOptions(antialias=True)
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
win = pg.GraphicsWindow()
win.setWindowTitle(args.title)
args.file = open(args.file) if args.file != '-' else sys.stdin
i = InputThread(args.file,args.num_samples,args.quiet)
i.start()
def handleKeyPress(e):
if e.text() == 'q':
os._exit(0)
elif e.text() == ' ':
if i.pause.isSet(): i.pause.clear()
else: i.pause.set()
win.keyPressEvent = handleKeyPress
cvn = win.addPlot()
plt = LinePlot(i,cvn,args.num_samples)
tmr = pg.QtCore.QTimer()
tmr.timeout.connect(plt)
tmr.start(30)
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()