[2bf92f2] | 1 | """Prototype plottable object support. |
---|
| 2 | |
---|
| 3 | The main point of this prototype is to provide a clean separation between |
---|
| 4 | the style (plotter details: color, grids, widgets, etc.) and substance |
---|
| 5 | (application details: which information to plot). Programmers should not be |
---|
| 6 | dictating line colours and plotting symbols. |
---|
| 7 | |
---|
| 8 | Unlike the problem of style in CSS or Word, where most paragraphs look |
---|
| 9 | the same, each line on a graph has to be distinguishable from its neighbours. |
---|
| 10 | Our solution is to provide parametric styles, in which a number of |
---|
| 11 | different classes of object (e.g., reflectometry data, reflectometry |
---|
| 12 | theory) representing multiple graph primitives cycle through a colour |
---|
| 13 | palette provided by the underlying plotter. |
---|
| 14 | |
---|
| 15 | A full treatment would provide perceptual dimensions of prominence and |
---|
| 16 | distinctiveness rather than a simple colour number. |
---|
| 17 | """ |
---|
| 18 | |
---|
| 19 | # Design question: who owns the color? |
---|
| 20 | # Is it a property of the plottable? |
---|
| 21 | # Or of the plottable as it exists on the graph? |
---|
| 22 | # Or if the graph? |
---|
| 23 | # If a plottable can appear on multiple graphs, in some case the |
---|
| 24 | # color should be the same on each graph in which it appears, and |
---|
| 25 | # in other cases (where multiple plottables from different graphs |
---|
| 26 | # coexist), the color should be assigned by the graph. In any case |
---|
| 27 | # once a plottable is placed on the graph its color should not |
---|
| 28 | # depend on the other plottables on the graph. Furthermore, if |
---|
| 29 | # a plottable is added and removed from a graph and added again, |
---|
| 30 | # it may be nice, but not necessary, to have the color persist. |
---|
| 31 | # |
---|
| 32 | # The safest approach seems to be to give ownership of color |
---|
| 33 | # to the graph, which will allocate the colors along with the |
---|
| 34 | # plottable. The plottable will need to return the number of |
---|
| 35 | # colors that are needed. |
---|
| 36 | # |
---|
| 37 | # The situation is less clear for symbols. It is less clear |
---|
| 38 | # how much the application requires that symbols be unique across |
---|
| 39 | # all plots on the graph. |
---|
| 40 | |
---|
| 41 | # Support for ancient python versions |
---|
| 42 | if 'any' not in dir(__builtins__): |
---|
| 43 | def any(L): |
---|
| 44 | for cond in L: |
---|
| 45 | if cond: return True |
---|
| 46 | return False |
---|
| 47 | def all(L): |
---|
| 48 | for cond in L: |
---|
| 49 | if not cond: return False |
---|
| 50 | return True |
---|
| 51 | |
---|
| 52 | # Graph structure for holding multiple plottables |
---|
| 53 | class Graph: |
---|
| 54 | """ |
---|
| 55 | Generic plottables graph structure. |
---|
| 56 | |
---|
| 57 | Plot styles are based on color/symbol lists. The user gets to select |
---|
| 58 | the list of colors/symbols/sizes to choose from, not the application |
---|
| 59 | developer. The programmer only gets to add/remove lines from the |
---|
| 60 | plot and move to the next symbol/color. |
---|
| 61 | |
---|
| 62 | Another dimension is prominence, which refers to line sizes/point sizes. |
---|
| 63 | |
---|
| 64 | Axis transformations allow the user to select the coordinate view |
---|
| 65 | which provides clarity to the data. There is no way we can provide |
---|
| 66 | every possible transformation for every application generically, so |
---|
| 67 | the plottable objects themselves will need to provide the transformations. |
---|
| 68 | Here are some examples from reflectometry: |
---|
| 69 | independent: x -> f(x) |
---|
| 70 | monitor scaling: y -> M*y |
---|
| 71 | log: y -> log(y if y > min else min) |
---|
| 72 | cos: y -> cos(y*pi/180) |
---|
| 73 | dependent: x -> f(x,y) |
---|
| 74 | Q4: y -> y*x^4 |
---|
| 75 | fresnel: y -> y*fresnel(x) |
---|
| 76 | coordinated: x,y = f(x,y) |
---|
| 77 | Q: x -> 2*pi/L (cos(x*pi/180) - cos(y*pi/180)) |
---|
| 78 | y -> 2*pi/L (sin(x*pi/180) + sin(y*pi/180)) |
---|
| 79 | reducing: x,y = f(x1,x2,y1,y2) |
---|
| 80 | spin asymmetry: x -> x1, y -> (y1 - y2)/(y1 + y2) |
---|
| 81 | vector net: x -> x1, y -> y1*cos(y2*pi/180) |
---|
| 82 | Multiple transformations are possible, such as Q4 spin asymmetry |
---|
| 83 | |
---|
| 84 | Axes have further complications in that the units of what are being |
---|
| 85 | plotted should correspond to the units on the axes. Plotting multiple |
---|
| 86 | types on the same graph should be handled gracefully, e.g., by creating |
---|
| 87 | a separate tab for each available axis type, breaking into subplots, |
---|
| 88 | showing multiple axes on the same plot, or generating inset plots. |
---|
| 89 | Ultimately the decision should be left to the user. |
---|
| 90 | |
---|
| 91 | Graph properties such as grids/crosshairs should be under user control, |
---|
| 92 | as should the sizes of items such as axis fonts, etc. No direct |
---|
| 93 | access will be provided to the application. |
---|
| 94 | |
---|
| 95 | Axis limits are mostly under user control. If the user has zoomed or |
---|
| 96 | panned then those limits are preserved even if new data is plotted. |
---|
| 97 | The exception is when, e.g., scanning through a set of related lines |
---|
| 98 | in which the user may want to fix the limits so that user can compare |
---|
| 99 | the values directly. Another exception is when creating multiple |
---|
| 100 | graphs sharing the same limits, though this case may be important |
---|
| 101 | enough that it is handled by the graph widget itself. Axis limits |
---|
| 102 | will of course have to understand the effects of axis transformations. |
---|
| 103 | |
---|
| 104 | High level plottable objects may be composed of low level primitives. |
---|
| 105 | Operations such as legend/hide/show copy/paste, etc. need to operate |
---|
| 106 | on these primitives as a group. E.g., allowing the user to have a |
---|
| 107 | working canvas where they can drag lines they want to save and annotate |
---|
| 108 | them. |
---|
| 109 | |
---|
| 110 | Graphs need to be printable. A page layout program for entire plots |
---|
| 111 | would be nice. |
---|
| 112 | """ |
---|
| 113 | def xaxis(self,name,units): |
---|
| 114 | """Properties of the x axis. |
---|
| 115 | """ |
---|
| 116 | if self.prop["xunit"] and units != self.prop["xunit"]: |
---|
| 117 | pass |
---|
| 118 | #print "Plottable: how do we handle non-commensurate units" |
---|
| 119 | self.prop["xlabel"] = "%s (%s)"%(name,units) |
---|
| 120 | self.prop["xunit"] = units |
---|
| 121 | |
---|
| 122 | def yaxis(self,name,units): |
---|
| 123 | """Properties of the y axis. |
---|
| 124 | """ |
---|
| 125 | if self.prop["xunit"] and units != self.prop["xunit"]: |
---|
| 126 | pass |
---|
| 127 | #print "Plottable: how do we handle non-commensurate units" |
---|
| 128 | self.prop["ylabel"] = "%s (%s)"%(name,units) |
---|
| 129 | self.prop["xunit"] = units |
---|
| 130 | |
---|
| 131 | def title(self,name): |
---|
| 132 | """Graph title |
---|
| 133 | """ |
---|
| 134 | self.prop["title"] = name |
---|
| 135 | |
---|
| 136 | def get(self,key): |
---|
| 137 | """Get the graph properties""" |
---|
| 138 | if key=="color": |
---|
| 139 | return self.color |
---|
| 140 | elif key == "symbol": |
---|
| 141 | return self.symbol |
---|
| 142 | else: |
---|
| 143 | return self.prop[key] |
---|
| 144 | |
---|
| 145 | def set(self,**kw): |
---|
| 146 | """Set the graph properties""" |
---|
| 147 | for key in kw: |
---|
| 148 | if key == "color": |
---|
| 149 | self.color = kw[key]%len(self.colorlist) |
---|
| 150 | elif key == "symbol": |
---|
| 151 | self.symbol = kw[key]%len(self.symbollist) |
---|
| 152 | else: |
---|
| 153 | self.prop[key] = kw[key] |
---|
| 154 | |
---|
| 155 | def isPlotted(self, plottable): |
---|
| 156 | """Return True is the plottable is already on the graph""" |
---|
| 157 | if plottable in self.plottables: |
---|
| 158 | return True |
---|
| 159 | return False |
---|
| 160 | |
---|
| 161 | def add(self,plottable): |
---|
| 162 | """Add a new plottable to the graph""" |
---|
| 163 | # record the colour associated with the plottable |
---|
| 164 | if not plottable in self.plottables: |
---|
| 165 | self.plottables[plottable]=self.color |
---|
| 166 | self.color += plottable.colors() |
---|
| 167 | |
---|
| 168 | def changed(self): |
---|
| 169 | """Detect if any graphed plottables have changed""" |
---|
| 170 | return any([p.changed() for p in self.plottables]) |
---|
| 171 | |
---|
| 172 | def delete(self,plottable): |
---|
| 173 | """Remove an existing plottable from the graph""" |
---|
| 174 | if plottable in self.plottables: |
---|
| 175 | del self.plottables[plottable] |
---|
| 176 | |
---|
| 177 | def reset(self): |
---|
| 178 | """Reset the graph.""" |
---|
| 179 | self.color = 0 |
---|
| 180 | self.symbol = 0 |
---|
| 181 | self.prop = {"xlabel":"", "xunit":None, |
---|
| 182 | "ylabel":"","yunit":None, |
---|
| 183 | "title":""} |
---|
| 184 | self.plottables = {} |
---|
| 185 | |
---|
| 186 | def _make_labels(self): |
---|
| 187 | # Find groups of related plottables |
---|
| 188 | sets = {} |
---|
| 189 | for p in self.plottables: |
---|
| 190 | if p.__class__ in sets: |
---|
| 191 | sets[p.__class__].append(p) |
---|
| 192 | else: |
---|
| 193 | sets[p.__class__] = [p] |
---|
| 194 | |
---|
| 195 | # Ask each plottable class for a set of unique labels |
---|
| 196 | labels = {} |
---|
| 197 | for c in sets: |
---|
| 198 | labels.update(c.labels(sets[c])) |
---|
| 199 | |
---|
| 200 | return labels |
---|
| 201 | |
---|
| 202 | def render(self,plot): |
---|
| 203 | """Redraw the graph""" |
---|
| 204 | plot.clear() |
---|
| 205 | plot.properties(self.prop) |
---|
| 206 | labels = self._make_labels() |
---|
| 207 | for p in self.plottables: |
---|
| 208 | p.render(plot,color=self.plottables[p],symbol=0,label=labels[p]) |
---|
| 209 | plot.render() |
---|
| 210 | |
---|
| 211 | def __init__(self,**kw): |
---|
| 212 | self.reset() |
---|
| 213 | self.set(**kw) |
---|
| 214 | |
---|
| 215 | |
---|
| 216 | # Transform interface definition |
---|
| 217 | # No need to inherit from this class, just need to provide |
---|
| 218 | # the same methods. |
---|
| 219 | class Transform: |
---|
| 220 | """Define a transform plugin to the plottable architecture. |
---|
| 221 | |
---|
| 222 | Transforms operate on axes. The plottable defines the |
---|
| 223 | set of transforms available for it, and the axes on which |
---|
| 224 | they operate. These transforms can operate on the x axis |
---|
| 225 | only, the y axis only or on the x and y axes together. |
---|
| 226 | |
---|
| 227 | This infrastructure is not able to support transformations |
---|
| 228 | such as log and polar plots as these require full control |
---|
| 229 | over the drawing of axes and grids. |
---|
| 230 | |
---|
| 231 | A transform has a number of attributes. |
---|
| 232 | |
---|
| 233 | name: user visible name for the transform. This will |
---|
| 234 | appear in the context menu for the axis and the transform |
---|
| 235 | menu for the graph. |
---|
| 236 | type: operational axis. This determines whether the |
---|
| 237 | transform should appear on x,y or z axis context |
---|
| 238 | menus, or if it should appear in the context menu for |
---|
| 239 | the graph. |
---|
| 240 | inventory: (not implemented) |
---|
| 241 | a dictionary of user settable parameter names and |
---|
| 242 | their associated types. These should appear as keyword |
---|
| 243 | arguments to the transform call. For example, Fresnel |
---|
| 244 | reflectivity requires the substrate density: |
---|
| 245 | { 'rho': type.Value(10e-6/units.angstrom**2) } |
---|
| 246 | Supply reasonable defaults in the callback so that |
---|
| 247 | limited plotting clients work even though they cannot |
---|
| 248 | set the inventory. |
---|
| 249 | """ |
---|
| 250 | |
---|
| 251 | def __call__(self,plottable,**kwargs): |
---|
| 252 | """Transform the data. Whenever a plottable is added |
---|
| 253 | to the axes, the infrastructure will apply all required |
---|
| 254 | transforms. When the user selects a different representation |
---|
| 255 | for the axes (via menu, script, or context menu), all |
---|
| 256 | plottables on the axes will be transformed. The |
---|
| 257 | plottable should store the underlying data but set |
---|
| 258 | the standard x,dx,y,dy,z,dz attributes appropriately. |
---|
| 259 | |
---|
| 260 | If the call raises a NotImplemented error the dataline |
---|
| 261 | will not be plotted. The associated string will usually |
---|
| 262 | be 'Not a valid transform', though other strings are possible. |
---|
| 263 | The application may or may not display the message to the |
---|
| 264 | user, along with an indication of which plottable was at fault. |
---|
| 265 | """ |
---|
| 266 | raise NotImplemented,"Not a valid transform" |
---|
| 267 | |
---|
| 268 | # Related issues |
---|
| 269 | # ============== |
---|
| 270 | # |
---|
| 271 | # log scale: |
---|
| 272 | # All axes have implicit log/linear scaling options. |
---|
| 273 | # |
---|
| 274 | # normalization: |
---|
| 275 | # Want to display raw counts vs detector efficiency correction |
---|
| 276 | # Want to normalize by time/monitor/proton current/intensity. |
---|
| 277 | # Want to display by eg. counts per 3 sec or counts per 10000 monitor. |
---|
| 278 | # Want to divide by footprint (ab initio, fitted or measured). |
---|
| 279 | # Want to scale by attenuator values. |
---|
| 280 | # |
---|
| 281 | # compare/contrast: |
---|
| 282 | # Want to average all visible lines with the same tag, and |
---|
| 283 | # display difference from one particular line. Not a transform |
---|
| 284 | # issue? |
---|
| 285 | # |
---|
| 286 | # multiline graph: |
---|
| 287 | # How do we show/hide data parts. E.g., data or theory, or |
---|
| 288 | # different polarization cross sections? One way is with |
---|
| 289 | # tags: each plottable has a set of tags and the tags are |
---|
| 290 | # listed as check boxes above the plotting area. Click a |
---|
| 291 | # tag and all plottables with that tag are hidden on the |
---|
| 292 | # plot and on the legend. |
---|
| 293 | # |
---|
| 294 | # nonconformant y-axes: |
---|
| 295 | # What do we do with temperature vs. Q and reflectivity vs. Q |
---|
| 296 | # on the same graph? |
---|
| 297 | # |
---|
| 298 | # 2D -> 1D: |
---|
| 299 | # Want various slices through the data. Do transforms apply |
---|
| 300 | # to the sliced data as well? |
---|
| 301 | |
---|
| 302 | |
---|
| 303 | class Plottable: |
---|
| 304 | def xaxis(self, name, units): |
---|
| 305 | self._xaxis = name |
---|
| 306 | self._xunit = units |
---|
| 307 | |
---|
| 308 | def yaxis(self, name, units): |
---|
| 309 | self._yaxis = name |
---|
| 310 | self._yunit = units |
---|
| 311 | |
---|
| 312 | @classmethod |
---|
| 313 | def labels(cls,collection): |
---|
| 314 | """ |
---|
| 315 | Construct a set of unique labels for a collection of plottables of |
---|
| 316 | the same type. |
---|
| 317 | |
---|
| 318 | Returns a map from plottable to name. |
---|
| 319 | """ |
---|
| 320 | n = len(collection) |
---|
| 321 | map = {} |
---|
| 322 | if n > 0: |
---|
| 323 | basename = str(cls).split('.')[-1] |
---|
| 324 | if n == 1: |
---|
| 325 | map[collection[0]] = basename |
---|
| 326 | else: |
---|
| 327 | for i in xrange(len(collection)): |
---|
| 328 | map[collection[i]] = "%s %d"%(basename,i) |
---|
| 329 | return map |
---|
| 330 | ##Use the following if @classmethod doesn't work |
---|
| 331 | # labels = classmethod(labels) |
---|
| 332 | |
---|
| 333 | def __init__(self): |
---|
| 334 | pass |
---|
| 335 | |
---|
| 336 | def render(self,plot): |
---|
| 337 | """The base class makes sure the correct units are being used for |
---|
| 338 | subsequent plottable. |
---|
| 339 | |
---|
| 340 | For now it is assumed that the graphs are commensurate, and if you |
---|
| 341 | put a Qx object on a Temperature graph then you had better hope |
---|
| 342 | that it makes sense. |
---|
| 343 | """ |
---|
| 344 | plot.xaxis(self._xaxis, self._xunit) |
---|
| 345 | plot.yaxis(self._yaxis, self._yunit) |
---|
| 346 | |
---|
| 347 | def colors(self): |
---|
| 348 | """Return the number of colors need to render the object""" |
---|
| 349 | return 1 |
---|
| 350 | |
---|
| 351 | |
---|
| 352 | class Data1D(Plottable): |
---|
| 353 | """Data plottable: scatter plot of x,y with errors in x and y. |
---|
| 354 | """ |
---|
| 355 | |
---|
| 356 | def __init__(self,x,y,dx=None,dy=None): |
---|
| 357 | """Draw points specified by x[i],y[i] in the current color/symbol. |
---|
| 358 | Uncertainty in x is given by dx[i], or by (xlo[i],xhi[i]) if the |
---|
| 359 | uncertainty is asymmetric. Similarly for y uncertainty. |
---|
| 360 | |
---|
| 361 | The title appears on the legend. |
---|
| 362 | The label, if it is different, appears on the status bar. |
---|
| 363 | """ |
---|
| 364 | self.x = x |
---|
| 365 | self.y = y |
---|
| 366 | self.dx = dx |
---|
| 367 | self.dy = dy |
---|
| 368 | |
---|
| 369 | def render(self,plot,**kw): |
---|
| 370 | Plottable.render(self,plot) |
---|
| 371 | plot.points(self.x,self.y,dx=self.dx,dy=self.dy,**kw) |
---|
| 372 | |
---|
| 373 | def changed(self): |
---|
| 374 | return False |
---|
| 375 | |
---|
| 376 | |
---|
| 377 | class Theory1D(Plottable): |
---|
| 378 | """Theory plottable: line plot of x,y with confidence interval y. |
---|
| 379 | """ |
---|
| 380 | def __init__(self,x,y,dy=None): |
---|
| 381 | """Draw lines specified in x[i],y[i] in the current color/symbol. |
---|
| 382 | Confidence intervals in x are given by dx[i] or by (xlo[i],xhi[i]) |
---|
| 383 | if the limits are asymmetric. |
---|
| 384 | |
---|
| 385 | The title is the name that will show up on the legend. |
---|
| 386 | """ |
---|
| 387 | self.x = x |
---|
| 388 | self.y = y |
---|
| 389 | |
---|
| 390 | self.dy = dy |
---|
| 391 | |
---|
| 392 | def render(self,plot,**kw): |
---|
| 393 | plot.curve(self.x,self.y,dy=self.dy,**kw) |
---|
| 394 | |
---|
| 395 | def changed(self): |
---|
| 396 | return False |
---|
| 397 | |
---|
| 398 | |
---|
| 399 | |
---|
| 400 | class Fit1D(Plottable): |
---|
| 401 | """Fit plottable: composed of a data line plus a theory line. This |
---|
| 402 | is treated like a single object from the perspective of the graph, |
---|
| 403 | except that it will have two legend entries, one for the data and |
---|
| 404 | one for the theory. |
---|
| 405 | |
---|
| 406 | The color of the data and theory will be shared.""" |
---|
| 407 | |
---|
| 408 | def __init__(self,data=None,theory=None): |
---|
| 409 | self.data=data |
---|
| 410 | self.theory=theory |
---|
| 411 | |
---|
| 412 | def render(self,plot,**kw): |
---|
| 413 | self.data.render(plot,**kw) |
---|
| 414 | self.theory.render(plot,**kw) |
---|
| 415 | |
---|
| 416 | def changed(self): |
---|
| 417 | return self.data.changed() or self.theory.changed() |
---|
| 418 | |
---|
| 419 | ###################################################### |
---|
| 420 | |
---|
| 421 | def sample_graph(): |
---|
| 422 | import numpy as nx |
---|
| 423 | |
---|
| 424 | # Construct a simple graph |
---|
| 425 | if False: |
---|
| 426 | x = nx.array([1,2,3,4,5,6],'d') |
---|
| 427 | y = nx.array([4,5,6,5,4,5],'d') |
---|
| 428 | dy = nx.array([0.2, 0.3, 0.1, 0.2, 0.9, 0.3]) |
---|
| 429 | else: |
---|
| 430 | x = nx.linspace(0,1.,10000) |
---|
| 431 | y = nx.sin(2*nx.pi*x*2.8) |
---|
| 432 | dy = nx.sqrt(100*nx.abs(y))/100 |
---|
| 433 | data = Data1D(x,y,dy=dy) |
---|
| 434 | data.xaxis('distance', 'm') |
---|
| 435 | data.yaxis('time', 's') |
---|
| 436 | graph = Graph() |
---|
| 437 | graph.title('Walking Results') |
---|
| 438 | graph.add(data) |
---|
| 439 | graph.add(Theory1D(x,y,dy=dy)) |
---|
| 440 | |
---|
| 441 | return graph |
---|
| 442 | |
---|
| 443 | def demo_plotter(graph): |
---|
| 444 | import wx |
---|
| 445 | #from pylab_plottables import Plotter |
---|
| 446 | from mplplotter import Plotter |
---|
| 447 | |
---|
| 448 | # Make a frame to show it |
---|
| 449 | app = wx.PySimpleApp() |
---|
| 450 | frame = wx.Frame(None,-1,'Plottables') |
---|
| 451 | plotter = Plotter(frame) |
---|
| 452 | frame.Show() |
---|
| 453 | |
---|
| 454 | # render the graph to the pylab plotter |
---|
| 455 | graph.render(plotter) |
---|
| 456 | |
---|
| 457 | class GraphUpdate: |
---|
| 458 | callnum=0 |
---|
| 459 | def __init__(self,graph,plotter): |
---|
| 460 | self.graph,self.plotter = graph,plotter |
---|
| 461 | def __call__(self): |
---|
| 462 | if self.graph.changed(): |
---|
| 463 | self.graph.render(self.plotter) |
---|
| 464 | return True |
---|
| 465 | return False |
---|
| 466 | def onIdle(self,event): |
---|
| 467 | #print "On Idle checker %d"%(self.callnum) |
---|
| 468 | self.callnum = self.callnum+1 |
---|
| 469 | if self.__call__(): |
---|
| 470 | pass # event.RequestMore() |
---|
| 471 | update = GraphUpdate(graph,plotter) |
---|
| 472 | frame.Bind(wx.EVT_IDLE,update.onIdle) |
---|
| 473 | app.MainLoop() |
---|
| 474 | |
---|
| 475 | import sys; print sys.version |
---|
| 476 | if __name__ == "__main__": |
---|
| 477 | demo_plotter(sample_graph()) |
---|
| 478 | |
---|