myFig_server.py 10.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# ================= FILE HEADER ========================================
#
#   myplotlib v3.0.1,
#
#   @file      myFig.py
#   @author    Yori 'AGy' Fournier
#   @licence   CC-BY-SA
#
#   MyFig class: Overlay of matplotlib Figure class
#   It is done such that the user can concentrate on
#   the important aspect of the figure and not the
#   technical part.
#
#   @Class MyFig
#
#   @Constructor
#
#                fignum:      number of the Figure.
#                reformat:    flag for reComputing plotted data
#                             from rawData.
#                debug:       flag for debugging, more verbatile.
#                (kw)args:    user defined arguments and keywords.
#
#   @section Functions
#
#            - printDebug:    print some debug information.
#
#            - plot:          overlay of Figure.plot() function,
#                             should be overwrited by the user.
#                             Consists of
#                             - creating axes,
#                             - formating the data,
#                             - adding the axis to the figure
#                             - plotting the axis
#
#            - update:        update the parameters in the
#                             keywords dictionary.
#
#   @section History
#
#   v 0.1.1 - MyFig class for the myplotlib module.
#
#   v 1.0.0 - Changed rawdata with inputarg to allows any type
#             of rawdata, can be an array.
#
#             replace the attribute format (reserved word) with
#             formatted.
#
#   v 1.0.1 - Suppress the explicit definitions of the keywords.
#             by the introduction of the keywords dictionary.
#             All parameters in this dictionary are automatically
#             updated.
#
#             suppress the default value of fignum and hardcode it
#             to be -1.
#
#             add the attribute boundedToWin required for the
#             interactive mode of myplotlib.
#
#   v 2.2.3 - Allow the possibility of giving a unique rawdata format
#             all axes. /!\ self.rawdata is a generator. /!\
#
# ======================================================================
#
#
# IMPORT ---------------------------------------------------------------
from . import os
from . import D_FIGSIZE, D_INPUTARG, D_DEBUG, D_REFORMAT, D_FORMATTED
from . import D_OFORMAT, D_OPATH
from . import DBUG, SEVR, INFO, SPCE, WARN
from . import MyData
#from . import MyAxes_server


# Class MyFig Overwriting Matplotlib.figure.Figure
class MyFig_server(object):
  
    # Set the size of the Figure in inch
    # (private variable can not be updated)
    FIGSIZE = D_FIGSIZE
84
85
    
    G_FIGNUM = 0 # This is to become global counter for myFig Instances to prevent ID collision
86
87
88
89
90
91
92
93
  
    # CONSTRUCTOR --------------------------------------------------------
    def __init__(self, rawdata, *args, **kwargs):
        
        # for the update function
        self._attributesToUpdateKeys = ['fignum', 'reformat', 'debug', 'formatted', 'aliases']
        
        # initialise the attribute default values and remove them from kwargs
94
        self.fignum       = kwargs.pop('fignum', MyFig_server.G_FIGNUM)  # need to be hard coded for interactive mode
95
96
97
98
99
100
101
102
103
104
105
106
        self.reformat     = kwargs.pop('reformat', D_REFORMAT)
        self.debug        = kwargs.pop('debug', D_DEBUG)
        self.formatted    = kwargs.pop('formatted', D_FORMATTED)
        self.aliases      = {}
        self.FIGSIZE      = kwargs.pop('figsize', self.FIGSIZE)

        self.axes = []
        
        # initialise
        self._initialize(*args, **kwargs)
        self.set_rawdata(rawdata)
    
107
108
109
        # count the global counter up by one
        MyFig_server.G_FIGNUM += 1

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
    # INITIALIZE -------------------------------------------------------
    def _initialize(self, *args, **kwargs):
        
        # add the axes
        self.addAxes()
        
        # declare the aliases
        self.declareAliases()
        
        # update the attributes and keywords
        self.update(**kwargs)
    
    # UPDATE ----------------------------------------------------------
    def update(self, **kwargs):
        
        # check attributes in keywords
        for keyword in kwargs.keys():
            
            # if it is the rawdata use the function
            if keyword == 'rawdata':
                self.set_rawdata(kwargs['rawdata'])
            
            # if it is an attribute
            elif keyword in self._attributesToUpdateKeys:
                # update value
                setattr(self, keyword, kwargs[keyword])
            
        # For each axes update the keywords
        for ax in self.get_axes():  # NEED TO CODE GET_AXES
                
            forax = {}
            
            for keyword in kwargs.keys():
                
                # ignore figure attributes
                if keyword in ['rawdata'] + self._attributesToUpdateKeys :
                    pass
                
                # Check if a key of kwargs has an alias for this axes
                elif keyword in self.aliases.keys():
                    alax, alkey = self.aliases[keyword]
            
                    # If an alias is found then update axkwargs
                    if ax == alax:
                        forax.update(**{alkey: kwargs[keyword]})
                
                # use keyword as it is for the axes
                else :
                    forax.update(**{keyword : kwargs[keyword]})
                
            # Then eventually all collected Keywords are updated in one go
            if (forax) :
                if self.debug:
                    print (DBUG+' fig.update ', ax, 'keywords: ', forax)
                ax.update(**forax)
        
        return(True)
    
168
169
170
171
    # GET FIG ID AS STRING --------------------------------------------
    def getFigID(self) :
        return str(self.fignum)
    
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
    # DECLARE ALIASES -------------------------------------------------
    def declareAliases(self):
        pass
    
    # ADD AXES ---------------------------------------------------------
    def addAxes(self, *arg, **kwargs):
        pass

    # GET_AXES ---------------------------------------------------------
    def get_axes(self):
        return(self.axes)
    
    # This overwrites MPL add_axes. It gives a name to the axis added so that it is easier to refer to
    def add_axes(self, ax, name) :
        
#        if isinstance(name, str) and issubclass(ax.__class__, MyAxes): # This lead to an error is ax is not in the same namespace
        ax.name = name
#        else:
#            print(SEVR + " there is an error with the input type of add_axes()")
#            return False
        
        # test if an axes with that name is already present
        for pax in self.get_axes() :
            if pax.name == name :
                print(SEVR + " an axes with that name is already present")
                return False
        
        self.axes.append(ax)
        
        return True
    
    # GET AXES BY NAME -------------------------------------------------
    def getAxesByName(self, name):
        
206
207
        for ax in self.get_axes():
            if ax.name == name:
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
                return ax
        
        #if the name is correct we should never get here.
        print(SEVR + "The axes name ", name, " was not found")
        return None
                
    
    # SET RAW DATA -----------------------------------------------------
    def set_rawdata(self, rawdata):
        
        from collections import Iterable
        from itertools import repeat
        
        self.formatted = False
        status = False
        
        # DEFAULT: one item per axes in figure
        if isinstance(rawdata, Iterable):
            
            if len(rawdata) == len(self.get_axes()):
                if(self.debug): print(DBUG + "set_rawdata: one item per axes")
                self.rawdata = rawdata
                status = self.formatRawData()
            
            else:
                self.rawdata = None
                print(SEVR + "rawdata should have the dimention of the number of axes: #axes = " + str(len(self.get_axes())) + "; dim of rawdata = " + str(len(rawdata)))
                return(False)
        
        # CONVINIENT: one object for all axes
        elif isinstance(rawdata, MyData):
            if(self.debug): print(DBUG + "set_rawdata: one item for all axes")
            self.rawdata = repeat(rawdata)  # This is the trick rawdata becomes a generator (so smart)
            status = self.formatRawData()
        
        else :
            print(SEVR + "set_rawdata: I could not set the rawdata...")
            self.rawdata = None
            status = False
        
        if not status:
            print(SEVR + "set_rawdata: I could not set the rawdata...")
            self.rawdata = None
        
        return(status)
    
    # FORMAT RAW DATA --------------------------------------------------
    def formatRawData(self):
        
        if self.rawdata is not None:
            
            for ax, rawdata in zip(self.get_axes(), self.rawdata):
                
                status = False
                
                if(self.debug):
                    print(INFO + "Axes: " + str(ax.__class__.__name__) + " with index " + str(self.get_axes().index(ax)) + " formats " + rawdata.name)
                    status = ax.testRawData(rawdata)
                    if status :
                        status = ax.formatRawData(rawdata)
                else:
                    status = ax.testRawData(rawdata)
                    if status:
                        try:
                            status = ax.formatRawData(rawdata)
                        except:
                            print(SEVR + "The " + str(ax.__class__.__name__) + " with index " + str(self.get_axes().index(ax)) + " could not format the rawdata.")
                            return(False)
                
                if not status:
                    return(False)
            
            if self.formatted is False:
                self.formatted = True
            
            return(True)
        
        else:
            return(False)
    
    # DEBUG --------------------------------------------------------------
    def printDebug(self):
        className = str(self.__class__.__name__)
        print('\n' + DBUG + "  {0} PARAMETERS: ".format(className))
        print(SPCE + "          Raw data: " + str(self.rawdata))
        print(SPCE + "     ID the figure: " + str(self.fignum))
        print(SPCE + "Size of the figure: " + str(self.FIGSIZE) + ' [inch] \n')