mpl_axes.py 9.82 KB
Newer Older
Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
1
2
3
4
5
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# ================= FILE HEADER ========================================
#
Philipp Gast's avatar
Philipp Gast committed
6
#   myplotlib v3.0.1,
Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#
#   @file      myAxes.py
#   @author    Yori 'AGy' Fournier
#   @licence   CC-BY-SA
#
#   MyAxes class: Overlay of matplotlib Axes class
#   It is done such that the user can concentrate on
#   the important aspect of the figure and not the
#   technical part. It consists of a constructor,
#   that requires a Figure, the ratio of the xaxis over
#   the yaxis, and the frame in which the figure
#   should be plotted.
#
#   @Class MyAxes
#
#   @Constructor(self, fig, ratio, frame, +user defined kw):
#
#   @section Functions
#
#            - plotting: this is the overwritten function
#                        from Axes. It is called by it's
#                        parent-figure's function .plot()
#
#            - formatRawData: it computes out of the rawData
#                        given as argument some quantities that
#                        are returned as a dictionary and
#                        become accessable for plotting.
#
#   @section History
#
#   v 0.0.0 - MyAxes class for the myplotlib module, consists
#             of a constructor, a pltting function and
#             formatRawData.
#
41
42
#   v 2.2.3 - Add testRawData function
#
Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
43
44
45
46
# ======================================================================
#
#
# IMPORT ---------------------------------------------------------------
47
from . import SEVR, DBUG
48
49
50
51
52
from . import CONTEXT

if CONTEXT.lower() != 'server':
    from . import Axes
    from . import rcParams
Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
53

54
_D_FRAME = [0.1, 0.1, 0.8, 0.8]
Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
55

56

57
# COMPUTE SMART FRAME -----------------------------------------------
58
59
def compute_fit_rect(fig, ratio, frame_rect):

60
    # get the frame allowed
61
    frame_pos_x, frame_pos_y, frame_width, frame_height = frame_rect
62
    # get the size of the figure
63
64
65
66
    fig_width = fig.get_figwidth()
    fig_height = fig.get_figheight()
    fig_dpi = fig.get_dpi()

67
    # get the font size in inches
68
69
    fontsize = rcParams['font.size'] / fig_dpi

70
    # the largest width and height allowed in inches
71
72
73
    max_width = fig_width * frame_width - 8. * (fig_dpi / 75.) * fontsize
    max_height = fig_height * frame_height - 4. * (fig_dpi / 75.) * fontsize

74
75
    # the hypothetical width and height in inches
    # for a given aspect ratio
76
77
78
    hypo_width = max_height / ratio
    hypo_height = max_width * ratio

79
80
81
    # if the hypothetical width is larger that the
    # maximum allowed width (in inches) then chose
    # the hypothetical Height
82
83
84
85
86
87
88
    if (hypo_width > max_width):
        height = hypo_height / fig_height  # height in percent
        width = max_width / fig_width     # width in percent
        pos_x = frame_pos_x + 4. * (fig_dpi / 75.) \
            * fontsize / fig_width      # posX
        pos_y = frame_pos_y + 3. * (fig_dpi / 75.) \
            * fontsize / fig_height     # posY
89
    else:
90
91
92
93
94
95
96
        height = max_height / fig_height
        width = hypo_width / fig_width
        pos_x = frame_pos_x + (frame_width - width) / 2.
        pos_y = frame_pos_y + 3. * (fig_dpi / 75.) * fontsize / fig_height

    rect = [pos_x, pos_y, width, height]

97
98
    return(rect)

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# Class Factory
class AxesClassFactory(type):


    # PREPARE METHOD --------------------------------------------------
    @classmethod
    def __prepare__(mcls, name, bases, **kwargs):
        return(type.__prepare__(mcls, name, bases))

    # NEW METHOD ------------------------------------------------------
    def __new__(mcls, name, bases, attrs, **kwargs):

#        context = kwargs.get('context', 'local')  # python3
        context = attrs.get('__context__', 'local')  # python2.7

        # Set the contextualized parent_constructor method
        parent_constructor = attrs.get('parent_constructor_'+str(context))
        if parent_constructor is not None:
            parent_constructor.__name__ = 'parent_constructor'
            attrs.update({'parent_constructor': parent_constructor})

        # Set the contextualized update method
        update = attrs.get('update_'+str(context))
        if update is not None:
            update.__name__ = 'update'
            attrs.update({'update': update})
        
        # Contextualize the bases for MplAxes
        if context in ('client', 'local'):
            if bases == (): # in the case of MplAxes
                bases = (Axes,)
        elif context == 'server':
            if bases == (): # in the case of MplAxes
                bases = (object,)
        else:
            print("{sevr} The context given in the configuration file \
            is not correct: should be either local, client or server. \
            ".format(sevr=SEVR))
            raise ImportError

        # Actually create the class
        axes_class = type.__new__(mcls, name, bases, attrs)

        return(axes_class)


    # INITIALIZATION METHOD -------------------------------------------
    def __init__(cls, name, bases, dct, **kwargs):
        super(AxesClassFactory, cls).__init__(name, bases, dct)

149

Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
150
# Class MyAxes Overwriting Matplotlib.figure.Axes
151
152
153
154
155
156
class MplAxes():

    __metaclass__ = AxesClassFactory
    __context__ = CONTEXT.lower()

    # --- SHARED METHODS -------------------------------------------------
157

Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
158
    # CONSTRUCTOR --------------------------------------------------------
159
    def __init__(self, fig, frame=_D_FRAME, **kwargs):
160

161
        self.fig = fig
162
        self.declare_keywords()
163

164
        # parent constructor
165
        self.parent_constructor(fig, frame, **kwargs)
166

167
        # set a default name. Should be individualized by instance
168
        self.name = 'default'
169

170
    # COMPUTE RECT -------------------------------------------------------
171
172
    def compute_rect(self, frame_rect, *args, **kwargs):

173
        # Get the optional keyword
174
        ratio = kwargs.pop('ratio', None)
175
176
177
178
        force_ratio_on_width = kwargs.pop('force_ratio_on_width', None)
        force_ratio_on_height = kwargs.pop('force_ratio_on_height', None)
        fit_in_frame = kwargs.pop('fit_in_frame', None)

Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
179
        # get the frame allowed
180
181
        frame_pos_x, frame_pos_y, frame_width, frame_height = frame_rect

182
        # get the size of the figure
183
184
185
        fig_width = self.fig.get_figwidth()
        fig_height = self.fig.get_figheight()

186
        if ratio is not None:
187
188
189
190
191

            if(force_ratio_on_width):
                frame_width = ratio * fig_width / (frame_height * fig_height)
            elif(force_ratio_on_height):
                frame_height = ratio * (frame_width * fig_width) / fig_height
192
            else:
193
194
195
196
197
198
                frame_height = ratio * (frame_width * fig_width) / fig_height

        rect = [frame_pos_x, frame_pos_y, frame_width, frame_height]

        if (fit_in_frame):

199
            if ratio is None:
200
201
202
203
                ratio = fig_height / fig_width

            rect = compute_fit_rect(self.fig, ratio, rect)

204
        return(rect)
205

206
    # DECLARE KEYWORDS -------------------------------------------------
207
    def declare_keywords(self):
Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
208
        self.keywords = {}
209

210
211
212
213
214
215
    # TESTING THE RAWDATA ----------------------------------------------
    def test_rawdata(self, rawdata):
        return(True)

    # --- INTERFACE METHODS --------------------------------------------
    
216
    # PLOTTING ---------------------------------------------------------
Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
217
    def plotting(self):
218
219
        raise(NotImplementedError, 'You should have overwrite the'
              ' plotting function.')
220
        return(False)
221
222

    # FORMATTING -------------------------------------------------------
223
224
225
    def format_rawdata(self, rawdata):
        raise(NotImplementedError, 'You should have overwritten the '
              'format_rawdata method.')
226
227
228
        return(False)    
    
    # --- ABSTRACT METHODS ---------------------------------------------
229

230
231
232
233
    # PARENT CONSTRUCTOR -----------------------------------------------
    def parent_constructor(self, fig, rect, **kwargs):
        raise(NotImplementedError, 'You should have overwritten the '
              'parent_constructor method.')
234

235
    # UPDATE -----------------------------------------------------------
236
    def update(self, *args, **kwargs):
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
        raise(NotImplementedError, 'You should have overwritten the '
              'update method.')

    # --- LOCAL/CLIENT CONTEXT METHODS ---------------------------------
    
    def parent_constructor_local(self, fig, frame, **kwargs):

        rect = self.compute_rect(frame, **kwargs)

        # clean kwargs
        kwargs.pop('ratio', None)
        kwargs.pop('force_ratio_on_width', None)
        kwargs.pop('force_ratio_on_height', None)
        kwargs.pop('fit_in_frame', None)
        
        Axes.__init__(self, fig, rect, **kwargs)

    def update_local(self, *args, **kwargs):
255

256
257
        # Because matplotlib.axes.update expect kwargs and not **kwargs
        # ... (stupid!! no, this is just WRONG!!)
258
        if args:  # catch matplotlib kwargs
259
            kwargs.update(args[0])
260
261
            # kw_for_axes = {key: value for (key, value) in args[0].items() if
            # key not in self.keywords}  # Not compatible with python2.6
262

263
264
265
266
        kw_for_axes = {}
        for (key, value) in kwargs.items():
            if key not in self.keywords:
                kw_for_axes.update({key: value})
267

268
        Axes.update(self, kw_for_axes)  # update matplotlib.Axes
269

270
        # myplotlib update
271
272
        # self.keywords.update({key: value for (key, value) in kwargs.items()
        # if key in self.keywords})  # Not compatible with python2.6
273

274
275
276
        for (key, value) in kwargs.items():
            if key in self.keywords:
                self.keywords.update({key: value})
277
278
279
280
281
282
283
284
285
286
287
288
289
        
    parent_constructor_client = parent_constructor_local
    update_client = update_local

    # --- SERVER CONTEXT METHODS --------------------------------------
        
    def parent_constructor_server(self, fig, frame, **kwargs):
        pass

    def update_server(self, *args, **kwargs):
        for (key, value) in kwargs.items():
            if key in self.keywords:
                self.keywords.update({key: value})