- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot.py
More file actions
Latest commit
380 lines (334 loc) · 11.2 KB
/
Copy pathplot.py
File metadata and controls
380 lines (334 loc) · 11.2 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
importfunctools
importmath
fromcollectionsimportdefaultdict
fromtypingimportUnion, Optional, List, Tuple
importnumpyasnp
importscipy
from .utilsimportexception_as_string
class_Figure(object):
def__init__(self):
self._options= {
"animation": False,
"responsive": True,
"showLines": False,
"maintainAspectRatio": False,
"tooltips": {
"enabled": False,
},
"scales": {
"yAxes": [],
"xAxes": [],
},
}
self._defaultXAxis=_Axis(True, "xax0")
self._defaultYAxis=_Axis(True, "yax0")
self._xaxes= [self._defaultXAxis]
self._yaxes= [self._defaultYAxis]
self._plots= []
self._interactive_plot=None
self.set_legend(display=False)
self.set_title("", display=False)
def_get_new_axis(self, is_X):
ifis_X:
ax=_Axis(True, "xax"+str(len(self._xaxes)))
self._xaxes.append(ax)
ifnotis_X:
ax=_Axis(True, "yax"+str(len(self._yaxes)))
self._yaxes.append(ax)
returnax
defadd_interactive_plot(self):
plot=_InteractivePlot(self, self._defaultXAxis, self._defaultYAxis, "interactive")
self._interactive_plot=plot
returnplot
def_get_interactive_plot(self):
returnself._interactive_plot
defget_new_plot(self):
plot=_Plot(self, self._defaultXAxis, self._defaultYAxis, str(len(self._plots)))
self._plots.append(plot)
returnplot
def_get_data(self, blocking : bool=True):
options=self._options
ifself._legendisnotNone:
options["legend"] =self._legend._get_data()
ifself._titleisnotNone:
options["title"] =self._title._get_data()
options["scales"]["xAxes"] = [ax._get_data() foraxinself._xaxes]
options["scales"]["yAxes"] = [ax._get_data() foraxinself._yaxes]
ifself._interactive_plotisnotNone:
all_plots=self._plots+ [self._interactive_plot]
else:
all_plots=self._plots
datasets= []
fori, pinenumerate(all_plots):
plot_data=p._get_data()
datasets.append(plot_data)
data= {"datasets": datasets}
return {
"data": data,
"error": "",
"options": options,
"interactive": self._interactive_plotisnotNone,
"defaultxmin": self._defaultXAxis.ax_min,
"defaultxmax": self._defaultXAxis.ax_max,
}
defset_title(self, *args, **kwargs):
self._title=_Title(*args, **kwargs)
defset_legend(self, *args, **kwargs):
self._legend=_Legend(*args, **kwargs)
defget_legend(self):
returnself._legend
class_Plot(object):
def__init__(self, fig, xax, yax, id_):
self._xaxis=xax
self._yaxis=yax
self.fig=fig
self.id_=id_
self._dataset= {
"label": self.id_,
"fill": False,
"tension": 0,
"backgroundColor": 'rgba(255, 255, 255, 0)',
"borderCapStyle": 'butt',
"borderDash": [],
"borderDashOffset": 0.0,
"borderJoinStyle": 'miter',
"pointBorderColor": 'rgba(0,0,0,1)',
"pointBackgroundColor": 'rgba(0,0,0,1)',
"pointBorderWidth": 1,
"pointHoverRadius": 5,
"pointHoverBorderColor": 'rgba(220,220,220,1)',
"pointRadius": 4,
"showLine": False,
"pointHitRadius": 3,
"yAxisID": "",
"xAxisID": "",
"data": [],
"datalabels": {
"display": False,
"color": "black",
"align": "right",
},
}
def_get_data(self):
data=self._dataset
data["xAxisID"] =self._xaxis.get_id()
data["yAxisID"] =self._yaxis.get_id()
returndata
def_normalize_array(self, arr):
res= []
forxinarr:
if'numpy'instr(type(x)):
res.append(float(x))
else:
res.append(x)
returnres
defscatter(self, xvals: List[float], yvals : List[float],
labels : Optional[List[str]] =None,
label_size : Optional[float] =None,
label_color : Optional[str] ="#000",
size : Optional[Union[float, List[float]]] =None,
color : Optional[Union[str, List[str]]] =None,
linecolor : str="#000"):
self._xlims=min(xvals), max(xvals)
self._ylims=min(yvals), max(yvals)
xvals=self._normalize_array(xvals)
yvals=self._normalize_array(yvals)
self._dataset["data"] = [{"x": x, "y": y} for (x, y) inzip(xvals, yvals)]
self._dataset["borderColor"] =linecolor
self._dataset["pointHoverBackgroundColor"] =linecolor
iflabelsisnotNone:
self._dataset["datalabels"]["display"] =True
self._dataset["datalabels"]["font"] = {}
self._dataset["datalabels"]["color"] =label_color
self._dataset["datalabels"]["font"]["size"] =label_size
self._dataset["data"] = [{"x": x, "y": y, "label": l} for (x, y, l) inzip(xvals, yvals, labels)]
else:
self._dataset["data"] = [{"x": x, "y": y} for (x, y) inzip(xvals, yvals)]
ifsizeisnotNone:
self._dataset["pointRadius"] =size
ifcolorisnotNone:
self._dataset["pointBackgroundColor"] =color
self._xaxis._update_data_lims(*self._xlims, self.id_)
self._yaxis._update_data_lims(*self._ylims, self.id_)
self.set_auto_lims()
# **kwargs passed to scatter() arguments
defplot(self, xvals : List[float], yvals : List[float], **kwargs):
self.scatter(xvals, yvals, **kwargs)
self._dataset["pointRadius"] =2
self._dataset["showLine"] =True
self._dataset["pointRadius"] =0
defget_xaxis(self):
returnself._xaxis
defget_yaxis(self):
returnself._yaxis
defset_auto_lims(self):
self._xaxis.set_auto_lims()
self._yaxis.set_auto_lims()
# if xax is None, creates a new one
defset_xaxis(self, xax : Optional["_Axis"] =None):
ifxaxisNone:
xax=self.fig._get_new_axis(True)
self._xaxis=xax
returnyax
# if yax is None, creates a new one
defset_yaxis(self, yax : Optional["_Axis"] =None):
ifyaxisNone:
yax=self.fig._get_new_axis(False)
self._yaxis=yax
returnyax
defset_label(self, label : str):
self._dataset["label"] =label
class_InteractivePlot(_Plot):
def__init__(self, *args):
super().__init__(*args)
deff(x):
returnx
self.f=f
self.func_params=None
STEP_COUNT_INIT=275
INC_TOL=20# must be even!
# The big challenge here is to figure out how many points we need in each
# part of the graph to make it smooth.
defget_result(self, params):
ifnotself.func_params:
return [], []
f_wrapped=functools.lru_cache(maxsize=40000)(self.f)
args= [params["parameters"][s] forsinself.func_params]
step= (params["xmax"] -params["xmin"]) /self.STEP_COUNT_INIT
xi=np.arange(params["xmin"], params["xmax"] +step, step) # +step for fencepost
step_sizes= [stepfor_inrange(xi.shape[0])]
it=0
whileTrue:
# get y values
yi= [f_wrapped(x, *args) forxinxi]
max_allowed_dy= (np.max(yi) -np.min(yi)) /120
dy=np.gradient(yi)
# check gradient
inc=dy>max_allowed_dy
ifnot (it<3andnp.any(inc)): break
# flag all the spots where the gradient is too big and areas nearby
padded=np.pad(inc, self.INC_TOL//2, "constant")
big=np.repeat(padded[None], self.INC_TOL, axis=0)
forix, jinenumerate(range(-self.INC_TOL//2, self.INC_TOL//2)):
big[ix] =np.roll(big[ix], j)
inc=np.max(big, axis=0)[self.INC_TOL//2: -self.INC_TOL//2]
# recalculate x values and save step sizes for each
new_xi= []
new_step_sizes= []
fori, vinenumerate(xi):
ss=step_sizes[i]
ifinc[i]:
new_xi.append(v-ss/3)
new_step_sizes.append(ss/3)
new_xi.append(v)
new_step_sizes.append(ss/3)
new_xi.append(v+ss/3)
new_step_sizes.append(ss/3)
else:
new_xi.append(v)
new_step_sizes.append(ss)
xi=new_xi
step_sizes=new_step_sizes
it+=1
returnlist(xi), yi
def_get_function_info(self, params):
try:
# exec string throws error or sets f as global
exec(params["code"], globals())
func_params_temp=list(f.__code__.co_varnames)[:f.__code__.co_argcount]
iffunc_params_temp[0] !="x":
raiseValueError("x not first argument of f.")
self.func_params=func_params_temp[1:]
self.f=f
return {"params": self.func_params, "error": None}
exceptExceptionase:
return {"error": exception_as_string(e), "params": []}
def_update_plot(self, params):
try:
xi, yi=self.get_result(params)
self.plot(xi, yi)
ifnotxi:
return {"error": None}
self._xaxis.set_lims(params["xmin"], params["xmax"])
if"ymin"inparams:
self._yaxis.set_lims(params["ymin"], params["ymax"])
else:
self._yaxis._update_data_lims(min(yi), max(yi), self.id_)
self._yaxis.set_auto_lims()
return {"error": None}
exceptExceptionase:
# print (exception_as_string(e))
return {"error": exception_as_string(e)}
defround_to_n(x, n):
returnround(x, -int(math.floor(math.log10(abs(x)))) + (n-1))
class_Axis(object):
def__init__(self, is_X, axis_id):
self.is_X=is_X
self.data= {
"id": axis_id,
"type": "linear",
"display": True,
"gridLines": {
"color": "lightgray",
"zeroLineColor": "black",
},
"ticks": {},
}
self.data_mins= {}
self.data_maxes= {}
self.step=None
defget_id(self):
returnself.data["id"]
defset_lims(self, new_min : float, new_max : float, stepSize : Optional[float] =None):
assertnew_min<new_max
self.step=stepSizeifstepSizeelseround_to_n((new_max-new_min) /12, 2)
self.ax_min=new_min
self.ax_max=new_max
defset_auto_lims(self):
data_max=max(self.data_maxes.values())
data_min=min(self.data_mins.values())
spread=data_max-data_min
self.set_lims(data_min-spread*0.1, data_max+spread*0.1)
def_update_data_lims(self, new_min, new_max, dataset_id):
self.data_mins[dataset_id] =new_min
self.data_maxes[dataset_id] =new_max
def_get_data(self):
data=self.data
data["ticks"]["min"] =self.ax_min
data["ticks"]["max"] =self.ax_max
data["ticks"]["stepSize"] =self.step
returndata
class_Legend(object):
def__init__(self, display : bool=False, position : str="top"):
self._data= {
"display": display,
"position": position
}
def_get_data(self):
returnself._data
defset_display(self, val : bool=True):
self._data["display"] =val
class_Title(object):
def__init__(self,
title : str,
display : bool=True,
fontSize : float=24,
fontFamily : str="'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
fontColor : str="#000",
fontStyle : str="bold",
padding : float=10,
line_height : float=1.2,
position : str="top",):
self._data= {
"display": display,
"text": title,
"fontSize": fontSize,
"fontFamily": fontFamily,
"fontColor": fontColor,
"fontStyle": fontStyle,
"padding": padding,
"line_height": line_height,
"position": position,
}
def_get_data(self):
returnself._data