source: sasview/src/sas/sasgui/plottools/plottables.py @ 1d4b9e5

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.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 1d4b9e5 was cd54205, checked in by Paul Kienzle <pkienzle@…>, 9 years ago

don't fail even when transformed data is empty

  • Property mode set to 100644
File size: 39.7 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
47import logging
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(object):
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_value = None
224        max_value = 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_value == None or x_i < min_value:
231                        min_value = x_i
232                    if max_value == None or x_i > max_value:
233                        max_value = x_i
234        return min_value, max_value
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(object):
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        label_dict = {}
508        if n > 0:
509            basename = str(cls).split('.')[-1]
510            if n == 1:
511                label_dict[collection[0]] = basename
512            else:
513                for i in xrange(len(collection)):
514                    label_dict[collection[i]] = "%s %d" % (basename, i)
515        return label_dict
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(object):
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            if not has_err_x:
707                dx = numpy.zeros(len(x))
708            if not has_err_y:
709                dy = numpy.zeros(len(y))
710            for i in range(len(x)):
711                try:
712                    tempx = self.funcx(x[i], y[i])
713                    tempy = self.funcy(y[i], x[i])
714                    if has_err_x:
715                        tempdx = self.funcdx(x[i], y[i], dx[i], dy[i])
716                    if has_err_y:
717                        tempdy = self.funcdy(y[i], x[i], dy[i], dx[i])
718                    self.x.append(tempx)
719                    self.y.append(tempy)
720                    if has_err_x:
721                        self.dx.append(tempdx)
722                    if has_err_y:
723                        self.dy.append(tempdy)
724                except Exception:
725                    pass
726            # Sanity check
727            if not len(self.x) == len(self.y):
728                msg = "Plottable.View: transformed x "
729                msg += "and y are not of the same length"
730                raise ValueError, msg
731            if has_err_x and not (len(self.x) == len(self.dx)):
732                msg = "Plottable.View: transformed x and dx"
733                msg += " are not of the same length"
734                raise ValueError, msg
735            if has_err_y and not (len(self.y) == len(self.dy)):
736                msg = "Plottable.View: transformed y"
737                msg += " and dy are not of the same length"
738                raise ValueError, msg
739            # Check that negative values are not plot on x and y axis for
740            # log10 transformation
741            self.check_data_logX()
742            self.check_data_logY()
743            # Store x ,y dx,and dy in their full range for reset
744            self.Xreel = self.x
745            self.Yreel = self.y
746            self.DXreel = self.dx
747            self.DYreel = self.dy
748
749    def onResetView(self):
750        """
751        Reset x,y,dx and y in their full range  and in the initial scale
752        in case their previous range has changed
753        """
754        self.x = self.Xreel
755        self.y = self.Yreel
756        self.dx = self.DXreel
757        self.dy = self.DYreel
758
759    def setTransformX(self, funcx, funcdx):
760        """
761        Receive pointers to function that transform x and dx
762        and set corresponding View pointers
763
764        :param transx: pointer to function that transforms x
765        :param transdx: pointer to function that transforms dx
766        """
767        self.funcx = funcx
768        self.funcdx = funcdx
769
770    def setTransformY(self, funcy, funcdy):
771        """
772        Receive pointers to function that transform y and dy
773        and set corresponding View pointers
774
775        :param transx: pointer to function that transforms y
776        :param transdx: pointer to function that transforms dy
777        """
778        self.funcy = funcy
779        self.funcdy = funcdy
780
781    def returnXview(self):
782        """
783        Return View  x,y,dx,dy
784        """
785        return self.x, self.y, self.dx, self.dy
786
787    def check_data_logX(self):
788        """
789        Remove negative value in x vector to avoid plotting negative
790        value of Log10
791        """
792        tempx = []
793        tempdx = []
794        tempy = []
795        tempdy = []
796        if self.dx == None:
797            self.dx = numpy.zeros(len(self.x))
798        if self.dy == None:
799            self.dy = numpy.zeros(len(self.y))
800        if self.xLabel == "log10(x)":
801            for i in range(len(self.x)):
802                try:
803                    if self.x[i] > 0:
804                        tempx.append(self.x[i])
805                        tempdx.append(self.dx[i])
806                        tempy.append(self.y[i])
807                        tempdy.append(self.dy[i])
808                except:
809                    logging.error("check_data_logX: skipping point x %g", self.x[i])
810                    logging.error(sys.exc_value)
811            self.x = tempx
812            self.y = tempy
813            self.dx = tempdx
814            self.dy = tempdy
815
816    def check_data_logY(self):
817        """
818        Remove negative value in y vector
819        to avoid plotting negative value of Log10
820
821        """
822        tempx = []
823        tempdx = []
824        tempy = []
825        tempdy = []
826        if self.dx == None:
827            self.dx = numpy.zeros(len(self.x))
828        if self.dy == None:
829            self.dy = numpy.zeros(len(self.y))
830        if self.yLabel == "log10(y)":
831            for i in range(len(self.x)):
832                try:
833                    if self.y[i] > 0:
834                        tempx.append(self.x[i])
835                        tempdx.append(self.dx[i])
836                        tempy.append(self.y[i])
837                        tempdy.append(self.dy[i])
838                except:
839                    logging.error("check_data_logY: skipping point %g", self.y[i])
840                    logging.error(sys.exc_value)
841
842            self.x = tempx
843            self.y = tempy
844            self.dx = tempdx
845            self.dy = tempdy
846
847    def onFitRangeView(self, xmin=None, xmax=None):
848        """
849        It limits View data range to plot from min to max
850
851        :param xmin: the minimum value of x to plot.
852        :param xmax: the maximum value of x to plot
853
854        """
855        tempx = []
856        tempdx = []
857        tempy = []
858        tempdy = []
859        if self.dx == None:
860            self.dx = numpy.zeros(len(self.x))
861        if self.dy == None:
862            self.dy = numpy.zeros(len(self.y))
863        if xmin != None and xmax != None:
864            for i in range(len(self.x)):
865                if self.x[i] >= xmin and self.x[i] <= xmax:
866                    tempx.append(self.x[i])
867                    tempdx.append(self.dx[i])
868                    tempy.append(self.y[i])
869                    tempdy.append(self.dy[i])
870            self.x = tempx
871            self.y = tempy
872            self.dx = tempdx
873            self.dy = tempdy
874
875
876class Data2D(Plottable):
877    """
878    2D data class for image plotting
879    """
880    def __init__(self, image=None, qx_data=None, qy_data=None,
881                 err_image=None, xmin=None, xmax=None, ymin=None,
882                 ymax=None, zmin=None, zmax=None):
883        """
884        Draw image
885        """
886        Plottable.__init__(self)
887        self.name = "Data2D"
888        self.label = None
889        self.data = image
890        self.qx_data = qx_data
891        self.qy_data = qx_data
892        self.err_data = err_image
893        self.source = None
894        self.detector = []
895
896        # # Units for Q-values
897        self.xy_unit = 'A^{-1}'
898        # # Units for I(Q) values
899        self.z_unit = 'cm^{-1}'
900        self._zaxis = ''
901        # x-axis unit and label
902        self._xaxis = '\\rm{Q_{x}}'
903        self._xunit = 'A^{-1}'
904        # y-axis unit and label
905        self._yaxis = '\\rm{Q_{y}}'
906        self._yunit = 'A^{-1}'
907
908        # ## might remove that later
909        # # Vector of Q-values at the center of each bin in x
910        self.x_bins = []
911        # # Vector of Q-values at the center of each bin in y
912        self.y_bins = []
913
914        # x and y boundaries
915        self.xmin = xmin
916        self.xmax = xmax
917        self.ymin = ymin
918        self.ymax = ymax
919
920        self.zmin = zmin
921        self.zmax = zmax
922        self.id = None
923
924    def xaxis(self, label, unit):
925        """
926        set x-axis
927
928        :param label: x-axis label
929        :param unit: x-axis unit
930
931        """
932        self._xaxis = label
933        self._xunit = unit
934
935    def yaxis(self, label, unit):
936        """
937        set y-axis
938
939        :param label: y-axis label
940        :param unit: y-axis unit
941
942        """
943        self._yaxis = label
944        self._yunit = unit
945
946    def zaxis(self, label, unit):
947        """
948        set z-axis
949
950        :param label: z-axis label
951        :param unit: z-axis unit
952
953        """
954        self._zaxis = label
955        self._zunit = unit
956
957    def setValues(self, datainfo=None):
958        """
959        Use datainfo object to initialize data2D
960
961        :param datainfo: object
962
963        """
964        self.image = copy.deepcopy(datainfo.data)
965        self.qx_data = copy.deepcopy(datainfo.qx_data)
966        self.qy_data = copy.deepcopy(datainfo.qy_data)
967        self.err_image = copy.deepcopy(datainfo.err_data)
968
969        self.xy_unit = datainfo.Q_unit
970        self.z_unit = datainfo.I_unit
971        self._zaxis = datainfo._zaxis
972
973        self.xaxis(datainfo._xunit, datainfo._xaxis)
974        self.yaxis(datainfo._yunit, datainfo._yaxis)
975        # x and y boundaries
976        self.xmin = datainfo.xmin
977        self.xmax = datainfo.xmax
978        self.ymin = datainfo.ymin
979        self.ymax = datainfo.ymax
980        # # Vector of Q-values at the center of each bin in x
981        self.x_bins = datainfo.x_bins
982        # # Vector of Q-values at the center of each bin in y
983        self.y_bins = datainfo.y_bins
984
985    def set_zrange(self, zmin=None, zmax=None):
986        """
987        """
988        if zmin < zmax:
989            self.zmin = zmin
990            self.zmax = zmax
991        else:
992            raise "zmin is greater or equal to zmax "
993
994    def render(self, plot, **kw):
995        """
996        Renders the plottable on the graph
997
998        """
999        plot.image(self.data, self.qx_data, self.qy_data,
1000                   self.xmin, self.xmax, self.ymin,
1001                   self.ymax, self.zmin, self.zmax, **kw)
1002
1003    def changed(self):
1004        """
1005        """
1006        return False
1007
1008    @classmethod
1009    def labels(cls, collection):
1010        """Build a label mostly unique within a collection"""
1011        label_dict = {}
1012        for item in collection:
1013            if item.label == "Data2D":
1014                item.label = item.name
1015            label_dict[item] = item.label
1016        return label_dict
1017
1018
1019class Data1D(Plottable):
1020    """
1021    Data plottable: scatter plot of x,y with errors in x and y.
1022    """
1023
1024    def __init__(self, x, y, dx=None, dy=None):
1025        """
1026        Draw points specified by x[i],y[i] in the current color/symbol.
1027        Uncertainty in x is given by dx[i], or by (xlo[i],xhi[i]) if the
1028        uncertainty is asymmetric.  Similarly for y uncertainty.
1029
1030        The title appears on the legend.
1031        The label, if it is different, appears on the status bar.
1032        """
1033        Plottable.__init__(self)
1034        self.name = "data"
1035        self.label = "data"
1036        self.x = x
1037        self.y = y
1038        self.dx = dx
1039        self.dy = dy
1040        self.source = None
1041        self.detector = None
1042        self.xaxis('', '')
1043        self.yaxis('', '')
1044        self.view = View(self.x, self.y, self.dx, self.dy)
1045        self.symbol = 0
1046        self.custom_color = None
1047        self.markersize = 5
1048        self.id = None
1049        self.zorder = 1
1050        self.hide_error = False
1051
1052    def render(self, plot, **kw):
1053        """
1054        Renders the plottable on the graph
1055        """
1056        if self.interactive == True:
1057            kw['symbol'] = self.symbol
1058            kw['id'] = self.id
1059            kw['hide_error'] = self.hide_error
1060            kw['markersize'] = self.markersize
1061            plot.interactive_points(self.view.x, self.view.y,
1062                                    dx=self.view.dx, dy=self.view.dy,
1063                                    name=self.name, zorder=self.zorder, **kw)
1064        else:
1065            kw['id'] = self.id
1066            kw['hide_error'] = self.hide_error
1067            kw['symbol'] = self.symbol
1068            kw['color'] = self.custom_color
1069            kw['markersize'] = self.markersize
1070            plot.points(self.view.x, self.view.y, dx=self.view.dx,
1071                        dy=self.view.dy, zorder=self.zorder,
1072                        marker=self.symbollist[self.symbol], **kw)
1073
1074    def changed(self):
1075        return False
1076
1077    @classmethod
1078    def labels(cls, collection):
1079        """Build a label mostly unique within a collection"""
1080        label_dict = {}
1081        for item in collection:
1082            if item.label == "data":
1083                item.label = item.name
1084            label_dict[item] = item.label
1085        return label_dict
1086
1087
1088class Theory1D(Plottable):
1089    """
1090    Theory plottable: line plot of x,y with confidence interval y.
1091    """
1092    def __init__(self, x, y, dy=None):
1093        """
1094        Draw lines specified in x[i],y[i] in the current color/symbol.
1095        Confidence intervals in x are given by dx[i] or by (xlo[i],xhi[i])
1096        if the limits are asymmetric.
1097
1098        The title is the name that will show up on the legend.
1099        """
1100        Plottable.__init__(self)
1101        msg = "Theory1D is no longer supported, please use Data1D and change symbol.\n"
1102        raise DeprecationWarning, msg
1103
1104class Fit1D(Plottable):
1105    """
1106    Fit plottable: composed of a data line plus a theory line.  This
1107    is treated like a single object from the perspective of the graph,
1108    except that it will have two legend entries, one for the data and
1109    one for the theory.
1110
1111    The color of the data and theory will be shared.
1112
1113    """
1114    def __init__(self, data=None, theory=None):
1115        """
1116        """
1117        Plottable.__init__(self)
1118        self.data = data
1119        self.theory = theory
1120
1121    def render(self, plot, **kw):
1122        """
1123        """
1124        self.data.render(plot, **kw)
1125        self.theory.render(plot, **kw)
1126
1127    def changed(self):
1128        """
1129        """
1130        return self.data.changed() or self.theory.changed()
1131
1132
1133# ---------------------------------------------------------------
1134class Text(Plottable):
1135    """
1136    """
1137    def __init__(self, text=None, xpos=0.5, ypos=0.9, name='text'):
1138        """
1139        Draw the user-defined text in plotter
1140        We can specify the position of text
1141        """
1142        Plottable.__init__(self)
1143        self.name = name
1144        self.text = text
1145        self.xpos = xpos
1146        self.ypos = ypos
1147
1148    def render(self, plot, **kw):
1149        """
1150        """
1151        from matplotlib import transforms
1152
1153        xcoords = transforms.blended_transform_factory(plot.subplot.transAxes,
1154                                                       plot.subplot.transAxes)
1155        plot.subplot.text(self.xpos,
1156                          self.ypos,
1157                          self.text,
1158                          label=self.name,
1159                          transform=xcoords)
1160
1161    def setText(self, text):
1162        """Set the text string."""
1163        self.text = text
1164
1165    def getText(self, text):
1166        """Get the text string."""
1167        return self.text
1168
1169    def set_x(self, x):
1170        """
1171        Set the x position of the text
1172        ACCEPTS: float
1173        """
1174        self.xpos = x
1175
1176    def set_y(self, y):
1177        """
1178        Set the y position of the text
1179        ACCEPTS: float
1180        """
1181        self.ypos = y
1182
1183
1184# ---------------------------------------------------------------
1185class Chisq(Plottable):
1186    """
1187    Chisq plottable plots the chisq
1188    """
1189    def __init__(self, chisq=None):
1190        """
1191        Draw the chisq in plotter
1192        We can specify the position of chisq
1193        """
1194        Plottable.__init__(self)
1195        self.name = "chisq"
1196        self._chisq = chisq
1197        self.xpos = 0.5
1198        self.ypos = 0.9
1199
1200    def render(self, plot, **kw):
1201        """
1202        """
1203        if  self._chisq == None:
1204            chisqTxt = r'$\chi^2=$'
1205        else:
1206            chisqTxt = r'$\chi^2=%g$' % (float(self._chisq))
1207
1208        from matplotlib import transforms
1209
1210        xcoords = transforms.blended_transform_factory(plot.subplot.transAxes,
1211                                                      plot.subplot.transAxes)
1212        plot.subplot.text(self.xpos,
1213                          self.ypos,
1214                          chisqTxt, label='chisq',
1215                          transform=xcoords)
1216
1217    def setChisq(self, chisq):
1218        """
1219        Set the chisq value.
1220        """
1221        self._chisq = chisq
1222
1223
1224######################################################
1225
1226def sample_graph():
1227    import numpy as nx
1228
1229    # Construct a simple graph
1230    if False:
1231        x = nx.array([1, 2, 3, 4, 5, 6], 'd')
1232        y = nx.array([4, 5, 6, 5, 4, 5], 'd')
1233        dy = nx.array([0.2, 0.3, 0.1, 0.2, 0.9, 0.3])
1234    else:
1235        x = nx.linspace(0, 1., 10000)
1236        y = nx.sin(2 * nx.pi * x * 2.8)
1237        dy = nx.sqrt(100 * nx.abs(y)) / 100
1238    data = Data1D(x, y, dy=dy)
1239    data.xaxis('distance', 'm')
1240    data.yaxis('time', 's')
1241    graph = Graph()
1242    graph.title('Walking Results')
1243    graph.add(data)
1244    graph.add(Theory1D(x, y, dy=dy))
1245    return graph
1246
1247
1248def demo_plotter(graph):
1249    import wx
1250    from pylab_plottables import Plotter
1251    # from mplplotter import Plotter
1252
1253    # Make a frame to show it
1254    app = wx.PySimpleApp()
1255    frame = wx.Frame(None, -1, 'Plottables')
1256    plotter = Plotter(frame)
1257    frame.Show()
1258
1259    # render the graph to the pylab plotter
1260    graph.render(plotter)
1261
1262    class GraphUpdate(object):
1263        callnum = 0
1264
1265        def __init__(self, graph, plotter):
1266            self.graph, self.plotter = graph, plotter
1267
1268        def __call__(self):
1269            if self.graph.changed():
1270                self.graph.render(self.plotter)
1271                return True
1272            return False
1273
1274        def onIdle(self, event):
1275            self.callnum = self.callnum + 1
1276            if self.__call__():
1277                pass  # event.RequestMore()
1278    update = GraphUpdate(graph, plotter)
1279    frame.Bind(wx.EVT_IDLE, update.onIdle)
1280    app.MainLoop()
Note: See TracBrowser for help on using the repository browser.