Commit 31713b2f authored by Philipp Gast's avatar Philipp Gast
Browse files

whitespace changes toward pep9 using autopep8 tool

parent bd6777c1
......@@ -49,19 +49,30 @@ np.set_printoptions(threshold='nan')
if D_HIERARCHY in ('CLIENT', 'client', 'LOCAL', 'local'):
if D_HIERARCHY in ('CLIENT', 'client'):
print(INFO+'Import '+__package__+' as a client.')
print(INFO + 'Import ' + __package__ + ' as a client.')
else:
print(INFO+'Import '+__package__+' for local use.')
print(INFO + 'Import ' + __package__ + ' for local use.')
# Test mpl version:
from matplotlib import __version__ as mplvers
if int(mplvers.replace('.', '')[:3]) < 143 :
print('\n\n' + WARN + 72*'=' + '\n' + SPCE
+ 'The matplotlib version you are using is not supported.\n'
+ SPCE + 'Most of myplotlib should work, but some stuff may not.\n'
+ SPCE + 'ex: expect an error with test203\n' + SPCE
+ 72 * '=' + '\n\n')
if int(mplvers.replace('.', '')[:3]) < 143:
print(
'\n\n' +
WARN +
72 *
'=' +
'\n' +
SPCE +
'The matplotlib version you are using is not supported.\n' +
SPCE +
'Most of myplotlib should work, but some stuff may not.\n' +
SPCE +
'ex: expect an error with test203\n' +
SPCE +
72 *
'=' +
'\n\n')
# matplotlib
from matplotlib.pyplot import figure
......@@ -70,7 +81,7 @@ if D_HIERARCHY in ('CLIENT', 'client', 'LOCAL', 'local'):
from matplotlib.pyplot import close as mpclose
from matplotlib.pyplot import fignum_exists, savefig
from matplotlib.axes import Axes
from matplotlib.figure import Figure_type
from matplotlib.figure import FigureType
from matplotlib import is_interactive
from matplotlib import use
......@@ -78,13 +89,13 @@ if D_HIERARCHY in ('CLIENT', 'client', 'LOCAL', 'local'):
from socket import socket, AF_INET, SOCK_STREAM
elif D_HIERARCHY in ('SERVER', 'server'):
if DBUG :
print(INFO+'Import '+__package__+' as a server.')
if DBUG:
print(INFO + 'Import ' + __package__ + ' as a server.')
from .config import D_HOST, D_PORT
from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
else:
print(SEVR+'the value of D_HIERARCHY has to be SERVER or CLIENT')
print(SEVR + 'the value of D_HIERARCHY has to be SERVER or CLIENT')
raise ImportError
# myplotlib
......@@ -128,17 +139,17 @@ elif(D_HIERARCHY in ('SERVER', 'server')):
# from .test import readStupidData, readStupidData2
SERVER_IOFUNCTIONS = {
# 'readStupidData': readStupidData,
# 'readStupidData2': readStupidData2
# 'readStupidData': readStupidData,
# 'readStupidData2': readStupidData2
}
SERVER_FIGURES = {
#'FigTest': FigTest
}
from .mplServer2 import MplServer2, MplHandler
elif D_HIERARCHY in ('LOCAL', 'local'):
# MyAxes: Overlay on matplotlib.Axes class
from .myAxes import MyAxes
......@@ -146,13 +157,13 @@ elif D_HIERARCHY in ('LOCAL', 'local'):
from .myFig import MyFig
from .mplGrid import Grid, VerticalGrid, HorizontalGrid
from .empty_fig import EmptyFig
from .empty_axes import EmptyAxes
else:
print(SEVR+'the value of D_HIERARCHY has to be SERVER, CLIENT or LOCAL')
print(SEVR + 'the value of D_HIERARCHY has to be SERVER, CLIENT or LOCAL')
raise ImportError
......@@ -172,18 +183,18 @@ if D_HIERARCHY in ('CLIENT', 'client', 'LOCAL', 'local'):
elif rcParams['backend'] == u'MacOSX':
from .myWin_MacOSx import MyWin_MacOSx as MyWin
else:
print(SEVR + """The backend you choosed is not
print(SEVR + """The backend you choosed is not
supported interactive mode not available""")
# myTool.*: interface functions to use myplotlib interactively
#from .mytool import print2file # need to make tools for server ?? or just put them in client/local
#from .mytool import FigOneAxes
# from .mytool import print2file # need to make tools for server ?? or just put them in client/local
#from .mytool import FigOneAxes
#if D_HIERARCHY in ('CLIENT', 'client', 'LOCAL', 'local'):
# if D_HIERARCHY in ('CLIENT', 'client', 'LOCAL', 'local'):
# from .mytool import print2file # need to make tools for server ?? or just put them in client/local
# from .mytool import FigOneAxes
# from .mytool import FigOneAxes
# from .mytool import window_exists, getCurrentWindowIDs
# from .mytool import print2file, print2screen, printListCurrentWindows
# from .mytool import getWindow, getFigOnWindow, drawFigOnWindow, giveDataToWindow
......
......@@ -97,16 +97,26 @@ for opt, arg in opts:
debug = True
elif opt in ("--server"):
run4server = True
run4server = True
# SECTION: TESTS ------------------------------------------------------
if run4Test:
if debug:
print(DBUG + '{title:{c}^{n}}'.format(title=' Run for Test ', c='=', n=72))
print(
DBUG +
'{title:{c}^{n}}'.format(
title=' Run for Test ',
c='=',
n=72))
else:
print(INFO + '{title:{c}^{n}}'.format(title=' Run for Test ', c='=', n=72))
print(
INFO +
'{title:{c}^{n}}'.format(
title=' Run for Test ',
c='=',
n=72))
fail = []
status = True
......@@ -114,8 +124,10 @@ if run4Test:
print(INFO + "TESTS: ")
for test in testList:
print('\n')
print(INFO + '{title:{c}^{n}}'.format(title=' ' + str(test.__name__) + ' ', c='=', n=72))
testStatus = myTest(test, True, fail, debug) # function, expected, fail, debug
print(INFO + '{title:{c}^{n}}'.format(title=' ' + \
str(test.__name__) + ' ', c='=', n=72))
# function, expected, fail, debug
testStatus = myTest(test, True, fail, debug)
if testStatus:
print(INFO + 72 * '-' + " [PASSED]")
else:
......
from .myData import MyData
# TECHNICAL ------------------------------------------------------------
D_VERSION='v5'
D_HIERARCHY='SERVER'
D_HOST='localhost'
D_PORT=50803
D_VERSION = 'v5'
D_HIERARCHY = 'SERVER'
D_HOST = 'localhost'
D_PORT = 50803
# FORM -----------------------------------------------------------------
INFO = " > info-: "
......
......@@ -27,7 +27,6 @@ class MplClient2():
self.connected = True
def disconnect(self):
''' shutdown socket. Warning:
If server and client are local the client can not shut down
the port because the server has still a handle on it'''
......@@ -197,10 +196,10 @@ class MplClient2():
# create a Signal of type Query with args
query = Query(Query.NEWSYNCFIGURE, {
'figClassName': figname.__name__,
"dataName": dataname,
'args': args,
'kwargs': kwargs})
'figClassName': figname.__name__,
"dataName": dataname,
'args': args,
'kwargs': kwargs})
status = self.send(query)
if not status:
......@@ -286,7 +285,7 @@ class MplClient2():
if debug:
if not status:
print(INFO+'Sent Signal')
print(INFO + 'Sent Signal')
formated_data = self.waitForSignal()
......
......@@ -46,14 +46,14 @@ class VerticalGrid(Grid):
def layout(self):
nbr_axes = len(self.items)
axes_height = (self.height - (nbr_axes-1)*self.padding
- 2.*self.margin) / nbr_axes
axes_height = (self.height - (nbr_axes - 1) * self.padding
- 2. * self.margin) / nbr_axes
for index in range(0, nbr_axes):
new_left = self.margin + self.left
new_bottom = self.margin + self.bottom \
+ index*axes_height \
+ index*self.padding
new_width = self.width - 2.*self.margin
+ index * axes_height \
+ index * self.padding
new_width = self.width - 2. * self.margin
new_height = axes_height
new_frame = [new_left, new_bottom, new_width, new_height]
self.items[index].set_position(new_frame)
......@@ -64,12 +64,12 @@ class HorizontalGrid(Grid):
def layout(self):
nbr_axes = len(self.items)
axes_width = (self.width - (nbr_axes - 1) * self.padding
- 2.*self.margin)/nbr_axes
- 2. * self.margin) / nbr_axes
for index in range(0, nbr_axes):
new_left = self.margin + self.left \
+ index*axes_width + index*self.padding
+ index * axes_width + index * self.padding
new_bottom = self.margin + self.bottom
new_width = axes_width
new_height = self.height - 2.*self.margin
new_height = self.height - 2. * self.margin
new_frame = [new_left, new_bottom, new_width, new_height]
self.items[index].set_position(new_frame)
......@@ -29,7 +29,7 @@ class MplHandler(SocketServer.StreamRequestHandler):
def dprint(*args):
# likewise for WARN,SPCE,SEVR,INFO :wprint,sprint,sevprint,iprint ?
argsl = list(args)
if type(argsl[0]) is str:
if isinstance(argsl[0], str):
argsl[0] = DBUG + argsl[0]
print(''.join([repr(arg) for arg in argsl]))
......@@ -83,7 +83,7 @@ class MplHandler(SocketServer.StreamRequestHandler):
# create the figure:
fig = fig_class(datas, **kwargs)
if debug:
print(INFO+"SERVER: I created the requested Figure")
print(INFO + "SERVER: I created the requested Figure")
except Exception as e:
if debug:
print(WARN + "SERVER: I could not"
......
......@@ -12,7 +12,7 @@ class MplUnpickler(pickle.Unpickler):
modulelist = module.split('.')
if 'myplotlib' in modulelist:
index = modulelist.index('myplotlib')
class_path = '.' + '.'.join(modulelist[index+1:])
class_path = '.' + '.'.join(modulelist[index + 1:])
module = own_module + class_path
return(getattr(sys.modules[module], name))
......@@ -192,7 +192,8 @@ class MyAxes(Axes):
# ... (stupid!! no, this is just WRONG!!)
if args: # catch matplotlib kwargs
kwargs.update(args[0])
# kw_for_axes = {key: value for (key, value) in args[0].items() if key not in self.keywords} # Not compatible with python2.6
# kw_for_axes = {key: value for (key, value) in args[0].items() if
# key not in self.keywords} # Not compatible with python2.6
kw_for_axes = {}
for (key, value) in kwargs.items():
......@@ -202,7 +203,8 @@ class MyAxes(Axes):
Axes.update(self, kw_for_axes) # update matplotlib.Axes
# myplotlib update
# self.keywords.update({key: value for (key, value) in kwargs.items() if key in self.keywords}) # Not compatible with python2.6
# self.keywords.update({key: value for (key, value) in kwargs.items()
# if key in self.keywords}) # Not compatible with python2.6
for (key, value) in kwargs.items():
if key in self.keywords:
......
......@@ -105,7 +105,8 @@ class MyAxesClient(Axes):
# Because matplotlib.axes.update expect kwargs and not **kwargs
if args: # catch matplotlib kwargs
kwargs = args[0]
# kw_for_axes = {key: value for (key, value) in args[0].items() if key not in self.keywords} # Not compatible with python2.6
# kw_for_axes = {key: value for (key, value) in args[0].items() if
# key not in self.keywords} # Not compatible with python2.6
kw_for_axes = {}
for (key, value) in args[0].items():
......@@ -115,7 +116,8 @@ class MyAxesClient(Axes):
Axes.update(self, kw_for_axes) # update matplotlib.Axes
# myplotlib update
# self.keywords.update({key: value for (key, value) in kwargs.items() if key in self.keywords}) # Not compatible with python2.6
# self.keywords.update({key: value for (key, value) in kwargs.items()
# if key in self.keywords}) # Not compatible with python2.6
for (key, value) in kwargs.items():
if key in self.keywords:
......
......@@ -74,7 +74,8 @@ class MyAxesServer(object):
def update(self, *args, **kwargs):
# myplotlib update
# self.keywords.update({key: value for (key, value) in kwargs.items() if key in self.keywords}) # Not compatible with python2.6
# self.keywords.update({key: value for (key, value) in kwargs.items()
# if key in self.keywords}) # Not compatible with python2.6
for (key, value) in kwargs.items():
if key in self.keywords:
......
......@@ -78,135 +78,140 @@ from . import Figure
# Class MyFig Overwriting Matplotlib.figure.Figure
class MyFig(Figure):
# Set the size of the Figure in inch
# (private variable can not be updated)
FIGSIZE = D_FIGSIZE
# CONSTRUCTOR --------------------------------------------------------
def __init__(self, rawdata, *args, **kwargs):
# for the update function
self._attributesToUpdateKeys = ['fignum', 'reformat', 'debug', 'formatted', 'aliases']
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 = {}
self.FIGSIZE = kwargs.pop('figsize', self.FIGSIZE)
# need to be hard coded for interactive mode
self.fignum = kwargs.pop('fignum', -1)
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)
# 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)
self.set_rawdata(rawdata)
# 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:
# treat aliases differently: do not replace value but update it
# for replacing the user need to call MyFig.aliases = replacement
# for replacing the user need to call MyFig.aliases =
# replacement
if keyword == 'aliases':
self.aliases.update(kwargs[keyword])
else:
# update value
setattr(self, keyword, kwargs[keyword])
# For each axes update the keywords
for ax in self.get_axes():
forax = {}
for keyword in kwargs.keys():
# ignore figure attributes
if keyword in ['rawdata'] + self._attributesToUpdateKeys :
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]})
else:
forax.update(**{keyword: kwargs[keyword]})
# Then eventually all collected Keywords are updated in one go
if (forax) :
if (forax):
if self.debug:
print (DBUG+' fig.update ', ax, 'keywords: ', forax)
print (DBUG + ' fig.update ', ax, 'keywords: ', forax)
ax.update(**forax)
return(True)
# DECLARE ALIASES -------------------------------------------------
def declareAliases(self):
pass
# ADD AXES ---------------------------------------------------------
def addAxes(self, *arg, **kwargs):
raise(NotImplementedError, 'The addAxes method needs to be implemented.')
# 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
# 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 :
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 :
for ax in self.get_axes():
if ax.name == name:
return ax
#if the name is correct we should never get here.
# if the name is correct we should never get here.
print(SEVR + "The axes name ", name, " was not found")
return None
......@@ -214,113 +219,132 @@ class MyFig(Figure):
def setLayout(self, grid):
self.layout = grid
self.layout.fig = self
# 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")
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)))
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)
if(self.debug):
print(DBUG + "set_rawdata: one item for all axes")
# This is the trick rawdata becomes a generator (so smart)
self.rawdata = repeat(rawdata)
status = self.formatRawData()
else :
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)
print(INFO +
"Axes: " +
str(ax.__class__.__name__) +
" with index " +
str(self.get_axes().index(ax)) +
" formats " +
rawdata.name)
status = ax.testRawData(rawdata)
if status :
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(