myFig_client.py 15.5 KB
Newer Older
Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
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
84
85
#!/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
from . import Figure


# Class MyFig Overwriting Matplotlib.figure.Figure
class MyFig_client(Figure):
  
    # Set the size of the Figure in inch
    # (private variable can not be updated)
    FIGSIZE = D_FIGSIZE
  
86
    # CONSTRUCTOR --------------------------------------------------------
Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
87
88
89
90
91
92
93
94
95
96
97
98
    # 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
        self.fignum       = kwargs.pop('fignum', -1)  # need to be hard coded for interactive mode
        self.reformat     = kwargs.pop('reformat', D_REFORMAT)
        self.debug        = kwargs.pop('debug', D_DEBUG)
        self.formatted    = kwargs.pop('formatted', D_FORMATTED)
        self.aliases      = {}
99
100
        self.syncID       = -1
        self.client       = None
Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
101
102
103
104
105
106
107
108
109
110
111
112
        self.FIGSIZE      = kwargs.pop('figsize', self.FIGSIZE)
        
        # parent constructor
        Figure.__init__(self, figsize=self.FIGSIZE)
        
        # This is required for the interactive mode
        # it ensures that a figure can not be bounded
        # to several windows and prevent the loss of canvas.
        self.boundedToWin = False
        
        # initialise
        self._initialize(*args, **kwargs)
113

114
115
116
117
118
119
120
121
    def deSyncFig(self):
        if self.client is not None :
            if self.client.deleteSyncFigure(self.syncID) :
                print('The figure was successfully deleted on the server Side')
                self.syncID = -1
            else :
                print('The figure could not be deleted on the server Side')
        else:
122
            print('The client is not connected to a server yet. Please use the client to set up a sync conection.')
123
    
124
125
126
127
128
129
    def getState(self) :
        """ this function collects the current state of in the figure by creating a dict that holds all keyword,value pairs (taking the aliases into account)
        
        Warning: myplotlib allows in a transparent manner to modify the axes directly. Those changes can not be covert.
        """
        state = dict()
130
        # test for double keywords and print a waring
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
        
        for ax in self.axes:
            
            # find aliases for this specific axes
            masks = dict()
            for alias in self.aliases.keys() :
                axes4alias,keyword = self.aliases[alias]
                if axes4alias == ax :
                    masks.update({keyword : alias})
            
            # collect all keywords of the axes and replace the keys with the aliases
            axKeywords = ax.keywords.copy()
            for mask in masks :
                if mask in axKeywords :
                    axKeywords[masks[mask]] = axKeywords.pop(mask)
            
147
148
149
150
151
            # Test if kewords are already set by an other axes
            for key in axKeywords.keys() :
                if key in state.keys():
                    print('Warning: The keyword \"',key,'\" appears in multiple axes. The Defaults will be overwritten. Prevent this by using aliases')
            
152
153
            # update the global keyword index
            state.update(axKeywords)
154
            
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
        return state
    
    def reSyncFig(self):
        
        if self.client is not None :
            
            # collect the current state of the figure
            state = self.getState()
            
            # call the client to recreate the figure on the server side and analyse the status.
            if self.client.reSyncFig(self.syncID,state) :
                print('The figure was successfully recreated on the server side')
                self.syncID = -1
            else :
                print('The figure could not be recreated on the server side')
        else:
            print('The client is not connected to a server yet. Please use the client to set up a sync conection.')
            
Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
173
174
175
176
177
178
179
180
181
182
    # INITIALIZE -------------------------------------------------------
    def _initialize(self, *args, **kwargs):
        
        # add the axes
        self.addAxes()
        
        # declare the aliases
        self.declareAliases()
        
        # update the attributes and keywords
183
184
185
186
187
188
        self._update(**kwargs)

    def _update(self, **kwargs):

        # check attributes in keywords
        for keyword in kwargs.keys():
189
                    
190
191
192
193
            # if it is an attribute
            if keyword in self._attributesToUpdateKeys:
                # update value
                setattr(self, keyword, kwargs[keyword])
194
                    
195
196
        # For each axes update the keywords
        for ax in self.get_axes():
197
                        
198
            forax = {}
199
                    
200
            for keyword in kwargs.keys():
201
                        
202
203
204
                # ignore figure attributes
                if keyword in self._attributesToUpdateKeys :
                    pass
205
                        
206
207
208
                # Check if a key of kwargs has an alias for this axes
                elif keyword in self.aliases.keys():
                    alax, alkey = self.aliases[keyword]
209
                    
210
211
212
                    # If an alias is found then update axkwargs
                    if ax == alax:
                        forax.update(**{alkey: kwargs[keyword]})
213
                        
214
215
216
                # use keyword as it is for the axes
                else :
                    forax.update(**{keyword : kwargs[keyword]})
217
                        
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
            # 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)        
        
    # UPDATE ----------------------------------------------------------
    def update(self, **kwargs):
        
        # send the keywords to the server
        if self.client is not None : 
            status = self.client.updateSyncFigure(self.syncID,kwargs)
            
            # if the server reported no errors apply the keywords on client side also:
            if status :
                self._update(**kwargs)
236
237
238
239
            else :
                print('The server reported of an error in setting the keywords')
                return(False)
        else :
240
241
            print(WARN+'The figure is not yet connected to a client')
            self._update(**kwargs)
242
            return(False)
Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
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
    
    # DECLARE ALIASES -------------------------------------------------
    def declareAliases(self):
        pass
    
    # ADD AXES ---------------------------------------------------------
    def addAxes(self, *arg, **kwargs):
        pass
    
    # 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
        
        Figure.add_axes(self, ax)
        
        return True
    
    # GET AXES BY NAME -------------------------------------------------
    def getAxesByName(self, name):
        
        for ax in self.get_axes() :
            if ax.name == name :
                return ax
        
        #if the name is correct we should never get here.
        print(SEVR + "The axes name ", name, " was not found")
        return None
281
282
283
284
285
286
287
        
    def getAxesName(self,unknownax) :
        """ compares all axes against the function parameter and returns the name of that axes if found in figure"""
        
        for ax in self.get_axes() :
            if unknownax == ax :
                return ax.name
Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
288
289
290
291
292
293
    
    # FORMAT RAW DATA --------------------------------------------------
    def formatRawData(self):
        # HEre comes a function that send a signal to the server
        # and tells him to execute the format rawdata of the
        # synchronized figure (server-side)
294
295
        if (self.client is not None) and (self.syncID != -1):

296
297
#            try:
            if (True):
298
                datas = self.client.syncFigFormatRawData(self.syncID)
299
300
301
#            except:
#                print(SEVR+'The server-side figure could not format the data...')
#                return(False)
302

303
            for ax, data in zip(self.get_axes(), datas):
304
                # each data is a string that can be unpacked by axes itself
305
306
#                ax.data = ax.unpackFormattedData(data)
                ax.data = data
307
308
309
310
311
312
                
        else:
            print(SEVR+'The figure is not properly synchronized.')
            return(False)

        return(True)
313
    
Yori 'AGy' Fournier's avatar
Yori 'AGy' Fournier committed
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
    # PLOT -------------------------------------------------------------
    def plot(self):
        
        status = True
        
        if(self.debug):
            print(DBUG + "currently formatting the data...")
        
        if((self.reformat) or (not self.formatted)):
            status = self.formatRawData()
            if(not status): return(False)
        
        if(self.debug):
            print(DBUG + "currently plotting the axes...")
        
        # For all axes in the figure reformat if needed and plot
        for ax in self.get_axes():
            
            # clean the axes
            ax.cla()
            
            # plot
            plottingStatus = ax.plotting()
            status = status and plottingStatus
        
        return(status)
    
    # RESET ------------------------------------------------------------
    def reset(self, *args, **kwargs):
        self.clf()
        self._initialize(*args, **kwargs)
        self.plot()
    
    # DEBUG --------------------------------------------------------------
    def printDebug(self):
        className = str(self.__class__.__name__)
        print('\n' + DBUG + "  {0} PARAMETERS: ".format(className))
        print(SPCE + "     ID the figure: " + str(self.fignum))
        print(SPCE + "Size of the figure: " + str(self.FIGSIZE) + ' [inch] \n')
    
    # PRINT 2 FILE -------------------------------------------------------
    def print2file(self, filename, *args, **kwargs):
        
        # get the keywords
        debug = kwargs.get('debug', D_DEBUG)
        oformat = kwargs.get('oformat', D_OFORMAT)
        opath = kwargs.get('opath', D_OPATH)
        as_seen = kwargs.get('as_seen', False)
        
        # set the dpi
        if(oformat == 'png'):
            dpi = 300.
            addMetaData = True  # NOT YET IMPLEENTED
        else:
            dpi = 100.
            addMetaData = False  # NOT YET IMPLEMENTED
        
        from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
        # if the figure is boundedToWin
        # save to canvas in a local variable and restore after saving to file.
        if self.boundedToWin:
            winCanvas = self.canvas
        else:
            winCanvas = None
            
        canvas = FigureCanvas(self)  # the canvas of the figure changed
        
        # Plot the figure
        if not as_seen:
            status = self.plot()
            if not status:
                print(SEVR + 'Can not plot the figure. sorry --> EXIT')
                return(False)
        
        # draw the figure on the new canvas
        canvas.draw()  # not really needed (savefig does that)
        
        # check if the extention is in the name
        if '.png' in str(filename):
            oformat = 'png'
            filename = filename[:-4]
        elif '.eps' in str(filename):
            oformat = 'eps'
            filename = filename[:-4]
        
        # check if the path is in the name
        if '/' in str(filename):
            if(debug):
                print(WARN + "I detect that the path is in the name of the file, will ignore D_OPATH.")
            arg = filename
            filename = os.path.basename(arg)
            opath = os.path.dirname(arg)
        
        # take care of the . in the extention
        if oformat[0] == '.':
            oformat = oformat[1:]
        
        # clean the output path
        if str(opath)[-1] == '/':
            opath = str(opath)[:-1]
        else:
            opath = str(opath)
        
        # print into a file
        try:
            self.savefig(str(opath) + '/' + str(filename) + '.' + str(oformat), dpi=dpi)  # ! this not the save from plt but from fig
        except IOError:
            print(SEVR + 'the path to the file does not exists:')
            print(SPCE + str(opath) + '/' + str(filename) + '.' + str(oformat) + ' --> EXIT')
            return(False)
        except:
            print(SEVR + 'Can not save file. sorry --> EXIT')
            return(False)
        
        # restore the former canvas
        if winCanvas is not None:
            self.canvas = winCanvas
        
        return(True)