source: sasview/src/sas/plottools/plottables.py @ e6e4af7

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since e6e4af7 was 79492222, checked in by krzywon, 10 years ago

Changed the file and folder names to remove all SANS references.

  • Property mode set to 100644
File size: 41.8 KB
Line 
1"""
2Prototype plottable object support.
3
4The main point of this prototype is to provide a clean separation between
5the style (plotter details: color, grids, widgets, etc.) and substance
6(application details: which information to plot).  Programmers should not be
7dictating line colours and plotting symbols.
8
9Unlike the problem of style in CSS or Word, where most paragraphs look
10the same, each line on a graph has to be distinguishable from its neighbours.
11Our solution is to provide parametric styles, in which a number of
12different classes of object (e.g., reflectometry data, reflectometry
13theory) representing multiple graph primitives cycle through a colour
14palette provided by the underlying plotter.
15
16A full treatment would provide perceptual dimensions of prominence and
17distinctiveness rather than a simple colour number.
18
19"""
20
21# Design question: who owns the color?
22# Is it a property of the plottable?
23# Or of the plottable as it exists on the graph?
24# Or if the graph?
25# If a plottable can appear on multiple graphs, in some case the
26# color should be the same on each graph in which it appears, and
27# in other cases (where multiple plottables from different graphs
28# coexist), the color should be assigned by the graph.  In any case
29# once a plottable is placed on the graph its color should not
30# depend on the other plottables on the graph.  Furthermore, if
31# a plottable is added and removed from a graph and added again,
32# it may be nice, but not necessary, to have the color persist.
33#
34# The safest approach seems to be to give ownership of color
35# to the graph, which will allocate the colors along with the
36# plottable.  The plottable will need to return the number of
37# colors that are needed.
38#
39# The situation is less clear for symbols.  It is less clear
40# how much the application requires that symbols be unique across
41# all plots on the graph.
42
43# Support for ancient python versions
44import copy
45import numpy
46import sys
47
48
49if 'any' not in dir(__builtins__):
50    def any(L):
51        for cond in L:
52            if cond:
53                return True
54        return False
55   
56    def all(L):
57        for cond in L:
58            if not cond:
59                return False
60        return True
61
62
63class Graph:
64    """
65    Generic plottables graph structure.
66   
67    Plot styles are based on color/symbol lists.  The user gets to select
68    the list of colors/symbols/sizes to choose from, not the application
69    developer.  The programmer only gets to add/remove lines from the
70    plot and move to the next symbol/color.
71
72    Another dimension is prominence, which refers to line sizes/point sizes.
73
74    Axis transformations allow the user to select the coordinate view
75    which provides clarity to the data.  There is no way we can provide
76    every possible transformation for every application generically, so
77    the plottable objects themselves will need to provide the transformations.
78    Here are some examples from reflectometry: ::
79   
80       independent: x -> f(x)
81          monitor scaling: y -> M*y
82          log:  y -> log(y if y > min else min)
83          cos:  y -> cos(y*pi/180)
84       dependent:   x -> f(x,y)
85          Q4:      y -> y*x^4
86          fresnel: y -> y*fresnel(x)
87       coordinated: x,y = f(x,y)
88          Q:    x -> 2*pi/L (cos(x*pi/180) - cos(y*pi/180))
89                y -> 2*pi/L (sin(x*pi/180) + sin(y*pi/180))
90       reducing: x,y = f(x1,x2,y1,y2)
91          spin asymmetry: x -> x1, y -> (y1 - y2)/(y1 + y2)
92          vector net: x -> x1, y -> y1*cos(y2*pi/180)
93         
94    Multiple transformations are possible, such as Q4 spin asymmetry
95
96    Axes have further complications in that the units of what are being
97    plotted should correspond to the units on the axes.  Plotting multiple
98    types on the same graph should be handled gracefully, e.g., by creating
99    a separate tab for each available axis type, breaking into subplots,
100    showing multiple axes on the same plot, or generating inset plots.
101    Ultimately the decision should be left to the user.
102
103    Graph properties such as grids/crosshairs should be under user control,
104    as should the sizes of items such as axis fonts, etc.  No direct
105    access will be provided to the application.
106
107    Axis limits are mostly under user control.  If the user has zoomed or
108    panned then those limits are preserved even if new data is plotted.
109    The exception is when, e.g., scanning through a set of related lines
110    in which the user may want to fix the limits so that user can compare
111    the values directly.  Another exception is when creating multiple
112    graphs sharing the same limits, though this case may be important
113    enough that it is handled by the graph widget itself.  Axis limits
114    will of course have to understand the effects of axis transformations.
115
116    High level plottable objects may be composed of low level primitives.
117    Operations such as legend/hide/show copy/paste, etc. need to operate
118    on these primitives as a group.  E.g., allowing the user to have a
119    working canvas where they can drag lines they want to save and annotate
120    them.
121
122    Graphs need to be printable.  A page layout program for entire plots
123    would be nice.
124   
125    """
126    def _xaxis_transformed(self, name, units):
127        """
128        Change the property of the x axis
129        according to an axis transformation
130        (as opposed to changing the basic properties)
131        """
132        if units != "":
133            name = "%s (%s)" % (name, units)
134        self.prop["xlabel"] = name
135        self.prop["xunit"] = units
136       
137    def _yaxis_transformed(self, name, units):
138        """
139        Change the property of the y axis
140        according to an axis transformation
141        (as opposed to changing the basic properties)
142        """
143        if units != "":
144            name = "%s (%s)" % (name, units)
145        self.prop["ylabel"] = name
146        self.prop["yunit"] = units
147       
148    def xaxis(self, name, units):
149        """
150        Properties of the x axis.
151        """
152        if units != "":
153            name = "%s (%s)" % (name, units)
154        self.prop["xlabel"] = name
155        self.prop["xunit"] = units
156        self.prop["xlabel_base"] = name
157        self.prop["xunit_base"] = units
158
159    def yaxis(self, name, units):
160        """
161        Properties of the y axis.
162        """
163        if units != "":
164            name = "%s (%s)" % (name, units)
165        self.prop["ylabel"] = name
166        self.prop["yunit"] = units
167        self.prop["ylabel_base"] = name
168        self.prop["yunit_base"] = units
169       
170    def title(self, name):
171        """
172        Graph title
173        """
174        self.prop["title"] = name
175       
176    def get(self, key):
177        """
178        Get the graph properties
179        """
180        if key == "color":
181            return self.color
182        elif key == "symbol":
183            return self.symbol
184        else:
185            return self.prop[key]
186
187    def set(self, **kw):
188        """
189        Set the graph properties
190        """
191        for key in kw:
192            if key == "color":
193                self.color = kw[key] % len(self.colorlist)
194            elif key == "symbol":
195                self.symbol = kw[key] % len(self.symbollist)
196            else:
197                self.prop[key] = kw[key]
198
199    def isPlotted(self, plottable):
200        """Return True is the plottable is already on the graph"""
201        if plottable in self.plottables:
202            return True
203        return False
204
205    def add(self, plottable, color=None):
206        """Add a new plottable to the graph"""
207        # record the colour associated with the plottable
208        if not plottable in self.plottables:
209            if color is not None:
210                self.plottables[plottable] = color
211            else:
212                self.color += plottable.colors()
213                self.plottables[plottable] = self.color
214
215    def changed(self):
216        """Detect if any graphed plottables have changed"""
217        return any([p.changed() for p in self.plottables])
218   
219    def get_range(self):
220        """
221        Return the range of all displayed plottables
222        """
223        min = None
224        max = None
225        for p in self.plottables:
226            if p.hidden == True:
227                continue
228            if not p.x == None:
229                for x_i in p.x:
230                    if min == None or x_i < min:
231                        min = x_i
232                    if max == None or x_i > max:
233                        max = x_i
234        return min, max
235   
236    def replace(self, plottable):
237        """Replace an existing plottable from the graph"""
238        selected_color = None
239        selected_plottable = None
240        for p in self.plottables.keys():
241            if plottable.id == p.id:
242                selected_plottable = p
243                selected_color = self.plottables[p]
244                break
245        if  selected_plottable is not None and selected_color is not None:
246            del self.plottables[selected_plottable]
247            self.plottables[plottable] = selected_color
248
249    def delete(self, plottable):
250        """Remove an existing plottable from the graph"""
251        if plottable in self.plottables:
252            del self.plottables[plottable]
253            self.color = len(self.plottables)
254           
255    def reset_scale(self):
256        """
257        Resets the scale transformation data to the underlying data
258        """
259        for p in self.plottables:
260            p.reset_view()
261
262    def reset(self):
263        """Reset the graph."""
264        self.color = -1
265        self.symbol = 0
266        self.prop = {"xlabel": "", "xunit": None,
267                     "ylabel": "", "yunit": None,
268                     "title": ""}
269        self.plottables = {}
270   
271    def _make_labels(self):
272        """
273        """
274        # Find groups of related plottables
275        sets = {}
276        for p in self.plottables:
277            if p.__class__ in sets:
278                sets[p.__class__].append(p)
279            else:
280                sets[p.__class__] = [p]
281        # Ask each plottable class for a set of unique labels
282        labels = {}
283        for c in sets:
284            labels.update(c.labels(sets[c]))
285        return labels
286   
287    def get_plottable(self, name):
288        """
289        Return the plottable with the given
290        name if it exists. Otherwise return None
291        """
292        for item in self.plottables:
293            if item.name == name:
294                return item
295        return None
296   
297    def returnPlottable(self):
298        """
299        This method returns a dictionary of plottables contained in graph
300        It is just by Plotpanel to interact with the complete list of plottables
301        inside the graph.
302        """
303        return self.plottables
304   
305    def render(self,plot):
306        """Redraw the graph"""
307        plot.connect.clearall()
308        plot.clear()
309        plot.properties(self.prop)
310        labels = self._make_labels()
311        for p in self.plottables:
312            if p.custom_color is not None:
313                p.render(plot, color=p.custom_color, symbol=0,
314                markersize=p.markersize, label=labels[p])
315            else:
316                p.render(plot, color=self.plottables[p], symbol=0,
317                     markersize=p.markersize, label=labels[p])
318        plot.render()
319   
320    def __init__(self, **kw):
321        self.reset()
322        self.set(**kw)
323        # Name of selected plottable, if any
324        self.selected_plottable = None
325
326
327# Transform interface definition
328# No need to inherit from this class, just need to provide
329# the same methods.
330class Transform:
331    """
332    Define a transform plugin to the plottable architecture.
333   
334    Transforms operate on axes.  The plottable defines the
335    set of transforms available for it, and the axes on which
336    they operate.  These transforms can operate on the x axis
337    only, the y axis only or on the x and y axes together.
338   
339    This infrastructure is not able to support transformations
340    such as log and polar plots as these require full control
341    over the drawing of axes and grids.
342   
343    A transform has a number of attributes.
344   
345    name
346      user visible name for the transform.  This will
347      appear in the context menu for the axis and the transform
348      menu for the graph.
349       
350    type
351      operational axis.  This determines whether the
352      transform should appear on x,y or z axis context
353      menus, or if it should appear in the context menu for
354      the graph.
355       
356    inventory
357      (not implemented)
358      a dictionary of user settable parameter names and
359      their associated types.  These should appear as keyword
360      arguments to the transform call.  For example, Fresnel
361      reflectivity requires the substrate density:
362      ``{ 'rho': type.Value(10e-6/units.angstrom**2) }``       
363      Supply reasonable defaults in the callback so that
364      limited plotting clients work even though they cannot
365      set the inventory.
366       
367    """
368    def __call__(self, plottable, **kwargs):
369        """
370        Transform the data.  Whenever a plottable is added
371        to the axes, the infrastructure will apply all required
372        transforms.  When the user selects a different representation
373        for the axes (via menu, script, or context menu), all
374        plottables on the axes will be transformed.  The
375        plottable should store the underlying data but set
376        the standard x,dx,y,dy,z,dz attributes appropriately.
377       
378        If the call raises a NotImplemented error the dataline
379        will not be plotted.  The associated string will usually
380        be 'Not a valid transform', though other strings are possible.
381        The application may or may not display the message to the
382        user, along with an indication of which plottable was at fault.
383       
384        """
385        raise NotImplemented, "Not a valid transform"
386
387    # Related issues
388    # ==============
389    #
390    # log scale:
391    #    All axes have implicit log/linear scaling options.
392    #
393    # normalization:
394    #    Want to display raw counts vs detector efficiency correction
395    #    Want to normalize by time/monitor/proton current/intensity.
396    #    Want to display by eg. counts per 3 sec or counts per 10000 monitor.
397    #    Want to divide by footprint (ab initio, fitted or measured).
398    #    Want to scale by attenuator values.
399    #
400    # compare/contrast:
401    #    Want to average all visible lines with the same tag, and
402    #    display difference from one particular line.  Not a transform
403    #    issue?
404    #
405    # multiline graph:
406    #    How do we show/hide data parts.  E.g., data or theory, or
407    #    different polarization cross sections?  One way is with
408    #    tags: each plottable has a set of tags and the tags are
409    #    listed as check boxes above the plotting area.  Click a
410    #    tag and all plottables with that tag are hidden on the
411    #    plot and on the legend.
412    #
413    # nonconformant y-axes:
414    #    What do we do with temperature vs. Q and reflectivity vs. Q
415    #    on the same graph?
416    #
417    # 2D -> 1D:
418    #    Want various slices through the data.  Do transforms apply
419    #    to the sliced data as well?
420
421
422class Plottable(object):
423    """
424    """
425    # Short ascii name to refer to the plottable in a menu
426    short_name = None
427    # Fancy name
428    name = None
429    # Data
430    x  = None
431    y  = None
432    dx = None
433    dy = None
434    # Parameter to allow a plot to be part of the list without being displayed
435    hidden = False
436    # Flag to set whether a plottable has an interactor or not
437    interactive = True
438    custom_color = None
439    markersize = 5  # default marker size is 'size 5'
440   
441    def __init__(self):
442        self.view = View()
443        self._xaxis = ""
444        self._xunit = ""
445        self._yaxis = ""
446        self._yunit = ""
447       
448    def __setattr__(self, name, value):
449        """
450        Take care of changes in View when data is changed.
451        This method is provided for backward compatibility.
452        """
453        object.__setattr__(self, name, value)
454        if name in ['x', 'y', 'dx', 'dy']:
455            self.reset_view()
456            #print "self.%s has been called" % name
457
458    def set_data(self, x, y, dx=None, dy=None):
459        """
460        """
461        self.x = x
462        self.y = y
463        self.dy = dy
464        self.dx = dx
465        self.transformView()
466   
467    def xaxis(self, name, units):
468        """
469        Set the name and unit of x_axis
470       
471        :param name: the name of x-axis
472        :param units: the units of x_axis
473       
474        """
475        self._xaxis = name
476        self._xunit = units
477
478    def yaxis(self, name, units):
479        """
480        Set the name and unit of y_axis
481       
482        :param name: the name of y-axis
483        :param units: the units of y_axis
484       
485        """
486        self._yaxis = name
487        self._yunit = units
488       
489    def get_xaxis(self):
490        """Return the units and name of x-axis"""
491        return self._xaxis, self._xunit
492   
493    def get_yaxis(self):
494        """ Return the units and name of y- axis"""
495        return self._yaxis, self._yunit
496
497    @classmethod
498    def labels(cls, collection):
499        """
500        Construct a set of unique labels for a collection of plottables of
501        the same type.
502       
503        Returns a map from plottable to name.
504       
505        """
506        n = len(collection)
507        map = {}
508        if n > 0:
509            basename = str(cls).split('.')[-1]
510            if n == 1:
511                map[collection[0]] = basename
512            else:
513                for i in xrange(len(collection)):
514                    map[collection[i]] = "%s %d" % (basename, i)
515        return map
516
517    ##Use the following if @classmethod doesn't work
518    # labels = classmethod(labels)
519    def setLabel(self, labelx, labely):
520        """
521        It takes a label of the x and y transformation and set View parameters
522       
523        :param transx: The label of x transformation is sent by Properties Dialog
524        :param transy: The label of y transformation is sent Properties Dialog
525       
526        """
527        self.view.xLabel = labelx
528        self.view.yLabel = labely
529   
530    def set_View(self, x, y):
531        """Load View"""
532        self.x = x
533        self.y = y
534        self.reset_view()
535       
536    def reset_view(self):
537        """Reload view with new value to plot"""
538        self.view = View(self.x, self.y, self.dx, self.dy)
539        self.view.Xreel = self.view.x
540        self.view.Yreel = self.view.y
541        self.view.DXreel = self.view.dx
542        self.view.DYreel = self.view.dy
543       
544    def render(self, plot):
545        """
546        The base class makes sure the correct units are being used for
547        subsequent plottable.
548       
549        For now it is assumed that the graphs are commensurate, and if you
550        put a Qx object on a Temperature graph then you had better hope
551        that it makes sense.
552       
553        """
554        plot.xaxis(self._xaxis, self._xunit)
555        plot.yaxis(self._yaxis, self._yunit)
556       
557    def is_empty(self):
558        """
559        Returns True if there is no data stored in the plottable
560        """
561        if not self.x == None and len(self.x) == 0 \
562            and not self.y == None and len(self.y) == 0:
563            return True
564        return False
565       
566    def colors(self):
567        """Return the number of colors need to render the object"""
568        return 1
569   
570    def transformView(self):
571        """
572        It transforms x, y before displaying
573        """
574        self.view.transform(self.x, self.y, self.dx, self.dy)
575       
576    def returnValuesOfView(self):
577        """
578        Return View parameters and it is used by Fit Dialog
579        """
580        return self.view.returnXview()
581   
582    def check_data_PlottableX(self):
583        """
584        Since no transformation is made for log10(x), check that
585        no negative values is plot in log scale
586        """
587        self.view.check_data_logX()
588       
589    def check_data_PlottableY(self):
590        """
591        Since no transformation is made for log10(y), check that
592        no negative values is plot in log scale
593        """
594        self.view.check_data_logY()
595       
596    def transformX(self, transx, transdx):
597        """
598        Receive pointers to function that transform x and dx
599        and set corresponding View pointers
600       
601        :param transx: pointer to function that transforms x
602        :param transdx: pointer to function that transforms dx
603       
604        """
605        self.view.setTransformX(transx, transdx)
606       
607    def transformY(self, transy, transdy):
608        """
609        Receive pointers to function that transform y and dy
610        and set corresponding View pointers
611       
612        :param transy: pointer to function that transforms y
613        :param transdy: pointer to function that transforms dy
614       
615        """
616        self.view.setTransformY(transy, transdy)
617       
618    def onReset(self):
619        """
620        Reset x, y, dx, dy view with its parameters
621        """
622        self.view.onResetView()
623       
624    def onFitRange(self, xmin=None, xmax=None):
625        """
626        It limits View data range to plot from min to max
627       
628        :param xmin: the minimum value of x to plot.
629        :param xmax: the maximum value of x to plot
630       
631        """
632        self.view.onFitRangeView(xmin, xmax)
633   
634   
635class View:
636    """
637    Representation of the data that might include a transformation
638    """
639    x = None
640    y = None
641    dx = None
642    dy = None
643
644    def __init__(self, x=None, y=None, dx=None, dy=None):
645        """
646        """
647        self.x = x
648        self.y = y
649        self.dx = dx
650        self.dy = dy
651        # To change x range to the reel range
652        self.Xreel = self.x
653        self.Yreel = self.y
654        self.DXreel = self.dx
655        self.DYreel = self.dy
656        # Labels of x and y received from Properties Dialog
657        self.xLabel = ""
658        self.yLabel = ""
659        # Function to transform x, y, dx and dy
660        self.funcx = None
661        self.funcy = None
662        self.funcdx = None
663        self.funcdy = None
664
665    def transform(self, x=None, y=None, dx=None, dy=None):
666        """
667        Transforms the x,y,dx and dy vectors and stores
668         the output in View parameters
669
670        :param x: array of x values
671        :param y: array of y values
672        :param dx: array of  errors values on x
673        :param dy: array of error values on y
674       
675        """
676        # Sanity check
677        # Do the transofrmation only when x and y are empty
678        has_err_x = not (dx == None or len(dx) == 0)
679        has_err_y = not (dy == None or len(dy) == 0)
680       
681        if(x != None) and (y != None):
682            if not dx == None and not len(dx) == 0 and not len(x) == len(dx):
683                msg = "Plottable.View: Given x and dx are not"
684                msg += " of the same length"
685                raise ValueError, msg
686            # Check length of y array
687            if not len(y) == len(x):
688                msg = "Plottable.View: Given y "
689                msg += "and x are not of the same length"
690                raise ValueError, msg
691       
692            if not dy == None and not len(dy) == 0 and not len(y) == len(dy):
693                msg = "Plottable.View: Given y and dy are not of the same "
694                msg += "length: len(y)=%s, len(dy)=%s" % (len(y), len(dy))
695                raise ValueError, msg
696            self.x = []
697            self.y = []
698            if has_err_x:
699                self.dx = []
700            else:
701                self.dx = None
702            if has_err_y:
703                self.dy = []
704            else:
705                self.dy = None
706            tempx = []
707            tempy = []
708            if not has_err_x:
709                dx = numpy.zeros(len(x))
710            if not has_err_y:
711                dy = numpy.zeros(len(y))
712            for i in range(len(x)):
713                try:
714                    tempx = self.funcx(x[i], y[i])
715                    tempy = self.funcy(y[i], x[i])
716                    if has_err_x:
717                        tempdx = self.funcdx(x[i], y[i], dx[i], dy[i])
718                    if has_err_y:
719                        tempdy = self.funcdy(y[i], x[i], dy[i], dx[i])
720                    self.x.append(tempx)
721                    self.y.append(tempy)
722                    if has_err_x:
723                        self.dx.append(tempdx)
724                    if has_err_y:
725                        self.dy.append(tempdy)
726                except:
727                    tempx = x[i]
728                    tempy = y[i]
729                    tempdy = dy[i]
730            # Sanity check
731            if not len(self.x) == len(self.y):
732                msg = "Plottable.View: transformed x "
733                msg += "and y are not of the same length"
734                raise ValueError, msg
735            if has_err_x and not (len(self.x) and len(self.dx)):
736                msg = "Plottable.View: transformed x and dx"
737                msg += " are not of the same length"
738                raise ValueError, msg
739            if has_err_y and not (len(self.y) and len(self.dy)):
740                msg = "Plottable.View: transformed y"
741                msg += " and dy are not of the same length"
742                raise ValueError, msg
743            # Check that negative values are not plot on x and y axis for
744            # log10 transformation
745            self.check_data_logX()
746            self.check_data_logY()
747            # Store x ,y dx,and dy in their full range for reset
748            self.Xreel = self.x
749            self.Yreel = self.y
750            self.DXreel = self.dx
751            self.DYreel = self.dy
752               
753    def onResetView(self):
754        """
755        Reset x,y,dx and y in their full range  and in the initial scale
756        in case their previous range has changed
757        """
758        self.x = self.Xreel
759        self.y = self.Yreel
760        self.dx = self.DXreel
761        self.dy = self.DYreel
762       
763    def setTransformX(self, funcx, funcdx):
764        """
765        Receive pointers to function that transform x and dx
766        and set corresponding View pointers
767       
768        :param transx: pointer to function that transforms x
769        :param transdx: pointer to function that transforms dx
770        """
771        self.funcx = funcx
772        self.funcdx = funcdx
773       
774    def setTransformY(self, funcy, funcdy):
775        """
776        Receive pointers to function that transform y and dy
777        and set corresponding View pointers
778       
779        :param transx: pointer to function that transforms y
780        :param transdx: pointer to function that transforms dy
781        """
782        self.funcy = funcy
783        self.funcdy = funcdy
784   
785    def returnXview(self):
786        """
787        Return View  x,y,dx,dy
788        """
789        return self.x, self.y, self.dx, self.dy
790   
791    def check_data_logX(self):
792        """
793        Remove negative value in x vector to avoid plotting negative
794        value of Log10
795        """
796        tempx = []
797        tempdx = []
798        tempy = []
799        tempdy = []
800        if self.dx == None:
801            self.dx = numpy.zeros(len(self.x))
802        if self.dy == None:
803            self.dy = numpy.zeros(len(self.y))
804        if self.xLabel == "log10(x)":
805            for i in range(len(self.x)):
806                try:
807                    if (self.x[i] > 0):
808                        tempx.append(self.x[i])
809                        tempdx.append(self.dx[i])
810                        tempy.append(self.y[i])
811                        tempdy.append(self.dy[i])
812                except:
813                    print "check_data_logX: skipping point x %g" % self.x[i]
814                    print sys.exc_value
815                    pass 
816            self.x = tempx
817            self.y = tempy
818            self.dx = tempdx
819            self.dy = tempdy
820       
821    def check_data_logY(self):
822        """
823        Remove negative value in y vector
824        to avoid plotting negative value of Log10
825       
826        """
827        tempx = []
828        tempdx = []
829        tempy = []
830        tempdy = []
831        if self.dx == None:
832            self.dx = numpy.zeros(len(self.x))
833        if self.dy == None:
834            self.dy = numpy.zeros(len(self.y))
835        if (self.yLabel == "log10(y)"):
836            for i in range(len(self.x)):
837                try:
838                    if (self.y[i] > 0):
839                        tempx.append(self.x[i])
840                        tempdx.append(self.dx[i])
841                        tempy.append(self.y[i])
842                        tempdy.append(self.dy[i])
843                except:
844                    print "check_data_logY: skipping point %g" % self.y[i]
845                    print sys.exc_value
846                    pass
847            self.x = tempx
848            self.y = tempy
849            self.dx = tempdx
850            self.dy = tempdy
851           
852    def onFitRangeView(self, xmin=None, xmax=None):
853        """
854        It limits View data range to plot from min to max
855       
856        :param xmin: the minimum value of x to plot.
857        :param xmax: the maximum value of x to plot
858       
859        """
860        tempx = []
861        tempdx = []
862        tempy = []
863        tempdy = []
864        if self.dx == None:
865            self.dx = numpy.zeros(len(self.x))
866        if self.dy == None:
867            self.dy = numpy.zeros(len(self.y))
868        if (xmin != None) and (xmax != None):
869            for i in range(len(self.x)):
870                if (self.x[i] >= xmin) and (self.x[i] <= xmax):
871                    tempx.append(self.x[i])
872                    tempdx.append(self.dx[i])
873                    tempy.append(self.y[i])
874                    tempdy.append(self.dy[i])
875            self.x = tempx
876            self.y = tempy
877            self.dx = tempdx
878            self.dy = tempdy
879
880             
881class Data2D(Plottable):
882    """
883    2D data class for image plotting
884    """
885    def __init__(self, image=None, qx_data=None, qy_data=None,
886                  err_image=None, xmin=None, xmax=None, ymin=None,
887                  ymax=None, zmin=None, zmax=None):
888        """
889        Draw image
890        """
891        Plottable.__init__(self)
892        self.name = "Data2D"
893        self.label = None
894        self.data = image
895        self.qx_data = qx_data
896        self.qy_data = qx_data
897        self.err_data = err_image
898        self.source = None
899        self.detector = []
900   
901        ## Units for Q-values
902        self.xy_unit = 'A^{-1}'
903        ## Units for I(Q) values
904        self.z_unit = 'cm^{-1}'
905        self._zaxis = ''
906        # x-axis unit and label
907        self._xaxis = '\\rm{Q_{x}}'
908        self._xunit = 'A^{-1}'
909        # y-axis unit and label
910        self._yaxis = '\\rm{Q_{y}}'
911        self._yunit = 'A^{-1}'
912       
913        ### might remove that later
914        ## Vector of Q-values at the center of each bin in x
915        self.x_bins = []
916        ## Vector of Q-values at the center of each bin in y
917        self.y_bins = []
918       
919        #x and y boundaries
920        self.xmin = xmin
921        self.xmax = xmax
922        self.ymin = ymin
923        self.ymax = ymax
924       
925        self.zmin = zmin
926        self.zmax = zmax
927        self.id = None
928       
929    def xaxis(self, label, unit):
930        """
931        set x-axis
932       
933        :param label: x-axis label
934        :param unit: x-axis unit
935       
936        """
937        self._xaxis = label
938        self._xunit = unit
939       
940    def yaxis(self, label, unit):
941        """
942        set y-axis
943       
944        :param label: y-axis label
945        :param unit: y-axis unit
946       
947        """
948        self._yaxis = label
949        self._yunit = unit
950       
951    def zaxis(self, label, unit):
952        """
953        set z-axis
954       
955        :param label: z-axis label
956        :param unit: z-axis unit
957       
958        """
959        self._zaxis = label
960        self._zunit = unit
961       
962    def setValues(self, datainfo=None):
963        """
964        Use datainfo object to initialize data2D
965       
966        :param datainfo: object
967       
968        """
969        self.image = copy.deepcopy(datainfo.data)
970        self.qx_data = copy.deepcopy(datainfo.qx_data)
971        self.qy_data = copy.deepcopy(datainfo.qy_data)
972        self.err_image = copy.deepcopy(datainfo.err_data)
973       
974        self.xy_unit = datainfo.Q_unit
975        self.z_unit = datainfo.I_unit
976        self._zaxis = datainfo._zaxis
977       
978        self.xaxis(datainfo._xunit, datainfo._xaxis)
979        self.yaxis(datainfo._yunit, datainfo._yaxis)
980        #x and y boundaries
981        self.xmin = datainfo.xmin
982        self.xmax = datainfo.xmax
983        self.ymin = datainfo.ymin
984        self.ymax = datainfo.ymax
985        ## Vector of Q-values at the center of each bin in x
986        self.x_bins = datainfo.x_bins
987        ## Vector of Q-values at the center of each bin in y
988        self.y_bins = datainfo.y_bins
989       
990    def set_zrange(self, zmin=None, zmax=None):
991        """
992        """
993        if zmin < zmax:
994            self.zmin = zmin
995            self.zmax = zmax
996        else:
997            raise "zmin is greater or equal to zmax "
998       
999    def render(self, plot, **kw):
1000        """
1001        Renders the plottable on the graph
1002       
1003        """
1004        plot.image(self.data, self.qx_data, self.qy_data,
1005                   self.xmin, self.xmax, self.ymin,
1006                   self.ymax, self.zmin, self.zmax, **kw)
1007       
1008    def changed(self):
1009        """
1010        """
1011        return False
1012   
1013    @classmethod
1014    def labels(cls, collection):
1015        """Build a label mostly unique within a collection"""
1016        map = {}
1017        for item in collection:
1018            #map[item] = label(item, collection)
1019            #map[item] = r"$\rm{%s}$" % item.name
1020            if item.label == "Data2D":
1021                item.label = item.name
1022            map[item] = item.label
1023        return map
1024
1025
1026class Data1D(Plottable):
1027    """
1028    Data plottable: scatter plot of x,y with errors in x and y.
1029    """
1030   
1031    def __init__(self, x, y, dx=None, dy=None):
1032        """
1033        Draw points specified by x[i],y[i] in the current color/symbol.
1034        Uncertainty in x is given by dx[i], or by (xlo[i],xhi[i]) if the
1035        uncertainty is asymmetric.  Similarly for y uncertainty.
1036
1037        The title appears on the legend.
1038        The label, if it is different, appears on the status bar.
1039        """
1040        Plottable.__init__(self)
1041        self.name = "data"
1042        self.label = "data"
1043        self.x = x
1044        self.y = y
1045        self.dx = dx
1046        self.dy = dy
1047        self.source = None
1048        self.detector = None
1049        self.xaxis('', '')
1050        self.yaxis('', '')
1051        self.view = View(self.x, self.y, self.dx, self.dy)
1052        self.symbol = 0
1053        self.custom_color = None
1054        self.markersize = 5
1055        self.id = None
1056        self.zorder = 1
1057        self.hide_error = False
1058     
1059    def render(self, plot, **kw):
1060        """
1061        Renders the plottable on the graph
1062        """
1063        if self.interactive == True:
1064            kw['symbol'] = self.symbol
1065            kw['id'] = self.id
1066            kw['hide_error'] = self.hide_error
1067            kw['markersize'] = self.markersize
1068            plot.interactive_points(self.view.x, self.view.y,
1069                                    dx=self.view.dx, dy=self.view.dy,
1070              name=self.name, zorder=self.zorder, **kw)
1071        else:
1072            kw['id'] =  self.id
1073            kw['hide_error'] = self.hide_error
1074            kw['symbol'] = self.symbol
1075            kw['color'] = self.custom_color
1076            kw['markersize'] = self.markersize
1077            plot.points(self.view.x, self.view.y, dx=self.view.dx,
1078                dy=self.view.dy, zorder=self.zorder, 
1079                marker=self.symbollist[self.symbol], **kw)
1080       
1081    def changed(self):
1082        return False
1083
1084    @classmethod
1085    def labels(cls, collection):
1086        """Build a label mostly unique within a collection"""
1087        map = {}
1088        for item in collection:
1089            #map[item] = label(item, collection)
1090            #map[item] = r"$\rm{%s}$" % item.name
1091            if item.label == "data":
1092                item.label = item.name
1093            map[item] = item.label
1094        return map
1095   
1096   
1097class Theory1D(Plottable):
1098    """
1099    Theory plottable: line plot of x,y with confidence interval y.
1100   
1101    """
1102    def __init__(self, x, y, dy=None):
1103        """
1104        Draw lines specified in x[i],y[i] in the current color/symbol.
1105        Confidence intervals in x are given by dx[i] or by (xlo[i],xhi[i])
1106        if the limits are asymmetric.
1107       
1108        The title is the name that will show up on the legend.
1109        """
1110        Plottable.__init__(self)
1111        msg = "Theory1D is no longer supported, please use Data1D and change"
1112        msg += " symbol.\n"
1113        raise DeprecationWarning, msg
1114        self.name = "theory"
1115        self.label = "theory"
1116        self.x = x
1117        self.y = y
1118        self.dy = dy
1119        self.xaxis('', '')
1120        self.yaxis('', '')
1121        self.view = View(self.x, self.y, None, self.dy)
1122        self.symbol = 0
1123        self.id = None
1124        self.zorder = 10
1125       
1126    def render(self, plot, **kw):
1127        """
1128        """
1129        if self.interactive == True:
1130            kw['id'] = self.id
1131            plot.interactive_curve(self.view.x, self.view.y,
1132                                   dy=self.view.dy,
1133                                   name=self.name, zorder=self.zorder, **kw)
1134        else:
1135            kw['id'] = self.id
1136            plot.curve(self.view.x, self.view.y, dy=self.view.dy, 
1137                       zorder=self.zorder, **kw)
1138           
1139    def changed(self):
1140        return False
1141   
1142    @classmethod
1143    def labels(cls, collection):
1144        """Build a label mostly unique within a collection"""
1145        map = {}
1146        for item in collection:
1147            if item.label == "theory":
1148                item.label = item.name
1149            map[item] = item.label
1150        return map
1151   
1152   
1153class Fit1D(Plottable):
1154    """
1155    Fit plottable: composed of a data line plus a theory line.  This
1156    is treated like a single object from the perspective of the graph,
1157    except that it will have two legend entries, one for the data and
1158    one for the theory.
1159
1160    The color of the data and theory will be shared.
1161   
1162    """
1163    def __init__(self, data=None, theory=None):
1164        """
1165        """
1166        Plottable.__init__(self)
1167        self.data = data
1168        self.theory = theory
1169
1170    def render(self, plot, **kw):
1171        """
1172        """
1173        self.data.render(plot, **kw)
1174        self.theory.render(plot, **kw)
1175
1176    def changed(self):
1177        """
1178        """
1179        return self.data.changed() or self.theory.changed()
1180
1181
1182# ---------------------------------------------------------------
1183class Text(Plottable):
1184    """
1185    """
1186    def __init__(self, text=None, xpos=0.5, ypos=0.9, name='text'):
1187        """
1188        Draw the user-defined text in plotter
1189        We can specify the position of text
1190        """
1191        Plottable.__init__(self)
1192        self.name = name
1193        self.text = text
1194        self.xpos = xpos
1195        self.ypos = ypos
1196       
1197    def render(self, plot, **kw):
1198        """
1199        """
1200        from matplotlib import transforms
1201
1202        xcoords = transforms.blended_transform_factory(plot.subplot.transAxes,
1203                                                       plot.subplot.transAxes)
1204        plot.subplot.text(self.xpos,
1205                          self.ypos,
1206                          self.text,
1207                          label=self.name,
1208                          transform=xcoords,
1209                          )
1210           
1211    def setText(self, text):
1212        """Set the text string."""
1213        self.text = text
1214
1215    def getText(self, text):
1216        """Get the text string."""
1217        return self.text
1218
1219    def set_x(self, x):
1220        """
1221        Set the x position of the text
1222        ACCEPTS: float
1223        """
1224        self.xpos = x
1225
1226    def set_y(self, y):
1227        """
1228        Set the y position of the text
1229        ACCEPTS: float
1230        """
1231        self.ypos = y
1232     
1233
1234# ---------------------------------------------------------------
1235class Chisq(Plottable):
1236    """
1237    Chisq plottable plots the chisq
1238    """
1239    def __init__(self, chisq=None):
1240        """
1241        Draw the chisq in plotter
1242        We can specify the position of chisq
1243        """
1244        Plottable.__init__(self)
1245        self.name = "chisq"
1246        #super( Chisq, self).__init__(None, None, None, None)
1247        self._chisq = chisq
1248        self.xpos = 0.5
1249        self.ypos = 0.9
1250       
1251    def render(self, plot, **kw):
1252        """
1253        """
1254        if  self._chisq == None:
1255            chisqTxt = r'$\chi^2=$'
1256        else:
1257            chisqTxt = r'$\chi^2=%g$' % (float(self._chisq))
1258
1259        from matplotlib import transforms
1260
1261        xcoords = transforms.blended_transform_factory(plot.subplot.transAxes,
1262                                                     plot.subplot.transAxes)
1263        plot.subplot.text(self.xpos,
1264                          self.ypos,
1265                          chisqTxt, label='chisq',
1266                          transform=xcoords,)
1267           
1268    def setChisq(self, chisq):
1269        """
1270        Set the chisq value.
1271        """
1272        self._chisq = chisq
1273
1274
1275######################################################
1276
1277def sample_graph():
1278    import numpy as nx
1279   
1280    # Construct a simple graph
1281    if False:
1282        x = nx.array([1,2,3,4,5,6], 'd')
1283        y = nx.array([4,5,6,5,4,5], 'd')
1284        dy = nx.array([0.2, 0.3, 0.1, 0.2, 0.9, 0.3])
1285    else:
1286        x = nx.linspace(0, 1., 10000)
1287        y = nx.sin(2 * nx.pi * x * 2.8)
1288        dy = nx.sqrt(100 * nx.abs(y)) / 100
1289    data = Data1D(x, y, dy=dy)
1290    data.xaxis('distance', 'm')
1291    data.yaxis('time', 's')
1292    graph = Graph()
1293    graph.title('Walking Results')
1294    graph.add(data)
1295    graph.add(Theory1D(x, y, dy=dy))
1296    return graph
1297
1298
1299def demo_plotter(graph):
1300    import wx
1301    from pylab_plottables import Plotter
1302    #from mplplotter import Plotter
1303
1304    # Make a frame to show it
1305    app = wx.PySimpleApp()
1306    frame = wx.Frame(None, -1, 'Plottables')
1307    plotter = Plotter(frame)
1308    frame.Show()
1309
1310    # render the graph to the pylab plotter
1311    graph.render(plotter)
1312   
1313    class GraphUpdate:
1314        callnum = 0
1315       
1316        def __init__(self, graph, plotter):
1317            self.graph, self.plotter = graph, plotter
1318       
1319        def __call__(self):
1320            if self.graph.changed():
1321                self.graph.render(self.plotter)
1322                return True
1323            return False
1324       
1325        def onIdle(self, event):
1326            self.callnum = self.callnum + 1
1327            if self.__call__(): 
1328                pass  # event.RequestMore()
1329    update = GraphUpdate(graph, plotter)
1330    frame.Bind(wx.EVT_IDLE, update.onIdle)
1331    app.MainLoop()
Note: See TracBrowser for help on using the repository browser.