Commit dc891f51 authored by Yori Fournier's avatar Yori Fournier
Browse files

Merge branch '88-cleanning-pep8-compilance' into 91-mpl-axes-factory

parents 91975266 bbc5a606
......@@ -117,7 +117,7 @@ if D_HIERARCHY in ('CLIENT', 'client'):
from .mpl_axes_client import MplAxesClient as MplAxes
from .mpl_grid import Grid, VerticalGrid, HorizontalGrid
# MplFig: Overlay on matplotlib.Figure class
from .mpl_fig_client import MplFigClient as MplFig
......@@ -127,11 +127,11 @@ if D_HIERARCHY in ('CLIENT', 'client'):
elif(D_HIERARCHY in ('SERVER', 'server')):
# MplAxes: Overlay on matplotlib.Axes class
# MplAxes: Overlay on matplotlib.Axes class
from .mpl_axes_server import MplAxesServer as MplAxes
from .mpl_grid import Grid, VerticalGrid, HorizontalGrid
# MplFig: Overlay on matplotlib.Figure class
from .mpl_fig_server import MplFigServer as MplFig
......@@ -140,7 +140,7 @@ elif(D_HIERARCHY in ('SERVER', 'server')):
# 'readStupidData2': readStupidData2
}
SERVER_FIGURES = {
#'FigTest': FigTest
# 'FigTest': FigTest
}
from .mpl_server import MplServer, MplHandler
......
......@@ -124,7 +124,7 @@ if run4Test:
print(INFO + "TESTS: ")
for test in testList:
print('\n')
print(INFO + '{title:{c}^{n}}'.format(title=' ' + \
print(INFO + '{title:{c}^{n}}'.format(title=' ' +
str(test.__name__) + ' ', c='=', n=72))
# function, expected, fail, debug
testStatus = myTest(test, True, fail, debug)
......
......@@ -55,12 +55,14 @@ class MplClient():
def send(self, sig):
""" Sending a Type derived from Signal through the socket
after 'pickling' it"""
print('prepare sending')
wf = self.sock.makefile(mode='wb')
if debug:
print('sending ',
type(sig),
' with content \"',
sig.content, '\"')
print('makefile done')
#~ if debug:
print('Client sending ',
type(sig),
' with content \"',
sig.content, '\"')
try:
pickle.dump(sig, wf)
except Exception:
......@@ -210,8 +212,8 @@ class MplClient():
# try to create a figure of the same class on the client side
if isinstance(answer, Answer):
print('''trying to create a figure of the same
class on the client side''')
print('trying to create a figure of the same '
'class on the client side')
fig = figname(dataname, *args, **kwargs)
# Link the temporary Sync Figure
fig.sync_id = answer.content
......@@ -298,7 +300,7 @@ class MplClient():
if formated_data.value:
print('This should not happen')
else:
print('instead if answer a error was received')
print('instead of answer a error was received')
datas = (None,)
else:
# set the figure data to answerSig.value
......
......@@ -110,7 +110,7 @@ class MplFig(Figure):
# add a default Grid to the figure
self.set_grid(HorizontalGrid())
# initialise
self._initialize(*args, **kwargs)
self.set_rawdata(rawdata)
......@@ -119,7 +119,9 @@ class MplFig(Figure):
def _initialize(self, *args, **kwargs):
# add the axes
self.addAxes() # This will throw a pep8 error but its needed to prevent confusion with matplotlib
self.addAxes()
# This will throw a pep8 error but its needed to prevent
# confusion with matplotlib -- need another name
# declare the aliases
self.declare_aliases()
......@@ -183,25 +185,28 @@ class MplFig(Figure):
def declare_aliases(self):
pass
# ADD AXES ---------------------------------------------------------
# ADD AXES --------------------------------------------------------
def addAxes(self, *arg, **kwargs):
raise(NotImplementedError, 'The addAxes method needs to be implemented.')
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
# 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()")
# print("{sevr} there is an error with the input type of \
# add_axes()".format(sevr=SEVR))
# 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")
print("{sevr} an axes with that name is already present\
".format(sevr=SEVR))
return False
Figure.add_axes(self, ax)
......@@ -216,7 +221,8 @@ class MplFig(Figure):
return ax
# if the name is correct we should never get here.
print(SEVR + "The axes name ", name, " was not found")
print("{sevr} The axes name {axes_name}, was not found\
".format(sevr=SEVR, axes_name=name))
return None
# SET LAYOUT -------------------------------------------------------
......@@ -227,7 +233,7 @@ class MplFig(Figure):
# LAYOUT -----------------------------------------------------------
def layout(self):
self.grid.layout()
# SET RAW DATA -----------------------------------------------------
def set_rawdata(self, rawdata):
......@@ -242,34 +248,40 @@ class MplFig(Figure):
if len(rawdata) == len(self.get_axes()):
if(self.debug):
print(DBUG + "set_rawdata: one item per axes")
print("{dbug} set_rawdata: one item per axes\
".format(dbug=DBUG))
self.rawdata = rawdata
status = self.format_rawdata()
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: nbr of axes={nbr_axes} ; \
dim of rawdata={len_rawdata} \
".format(sevr=SEVR,
nbr_axes=len(self.get_axes()),
len_rawdata=len(rawdata)))
return(False)
# CONVINIENT: one object for all axes
elif isinstance(rawdata, MplData):
if(self.debug):
print(DBUG + "set_rawdata: one item for all axes")
print("{dbug} set_rawdata: one item for all axes\
".format(dbug=DBUG))
# This is the trick rawdata becomes a generator (so smart)
self.rawdata = repeat(rawdata)
status = self.format_rawdata()
else:
print(SEVR + "set_rawdata: I could not set the rawdata...")
print("{sevr} set_rawdata: I could not set the rawdata...\
".format(sevr=SEVR))
self.rawdata = None
status = False
if not status:
print(SEVR + "set_rawdata: I could not set the rawdata...")
print("{sevr} set_rawdata: I could not set the rawdata...\
".format(sevr=SEVR))
self.rawdata = None
return(status)
......@@ -284,13 +296,12 @@ class MplFig(Figure):
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: {axes_class_name} \
with index {index} formats {rawdata_name}\
".format(info=INFO,
axes_class_name=ax.__class__.__name__,
index=self.get_axes().index(ax),
rawdata_name=rawdata.name))
status = ax.test_rawdata(rawdata)
if status:
status = ax.format_rawdata(rawdata)
......@@ -300,12 +311,11 @@ class MplFig(Figure):
try:
status = ax.format_rawdata(rawdata)
except BaseException:
print(SEVR +
"The " +
str(ax.__class__.__name__) +
" with index " +
str(self.get_axes().index(ax)) +
" could not format the rawdata.")
print("{sevr} The {axes_class_name} \
with index {index} could not format the rawdata.\
".format(sevr=SEVR,
axes_class_name=ax.__class__.__name__,
index=self.get_axes().index(ax)))
return(False)
if not status:
......@@ -325,7 +335,8 @@ class MplFig(Figure):
status = True
if(self.debug):
print(DBUG + "currently formatting the data...")
print("{dbug} currently formatting the data...\
".format(dbug=DBUG))
if((self.reformat) or (not self.formatted)):
status = self.format_rawdata()
......@@ -333,7 +344,8 @@ class MplFig(Figure):
return(False)
if(self.debug):
print(DBUG + "currently plotting the axes...")
print("{dbug} currently plotting the axes...\
".format(dbug=DBUG))
# For all axes in the figure reformat if needed and plot
for ax in self.get_axes():
......@@ -378,9 +390,11 @@ class MplFig(Figure):
dpi = 100.
add_metadata = False # NOT YET IMPLEMENTED
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
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.
# save to canvas in a local variable
# and restore after saving to file.
if self.bounded_to_win:
win_canvas = self.canvas
else:
......@@ -409,9 +423,10 @@ class MplFig(Figure):
# 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.")
print("{warn} I detect that the path is in \
the name of the file, will ignore D_OPATH.\
".format(warn=WARN))
arg = filename
filename = os.path.basename(arg)
opath = os.path.dirname(arg)
......
......@@ -123,12 +123,16 @@ class MplFigClient(Figure):
print('The figure could not be deleted 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.')
'The client is not connected to a server yet.'
'Please use the client to set up a sync conection.')
def get_state(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)
""" 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.
Warning: myplotlib allows in a transparent manner to modify
the axes directly. Those changes can not be covert.
"""
state = dict()
# test for double keywords and print a waring
......@@ -155,7 +159,8 @@ class MplFigClient(Figure):
print(
'Warning: The keyword \"',
key,
'\" appears in multiple axes. The Defaults will be overwritten. Prevent this by using aliases')
'\" appears in multiple axes. The Defaults will'
' be overwritten. Prevent this by using aliases')
# update the global keyword index
state.update(ax_keywords)
......@@ -178,7 +183,8 @@ class MplFigClient(Figure):
self.sync_id = new_fig.sync_id
else:
print(
'The client is not connected to a server yet. Please use the client to set up a sync conection.')
'The client is not connected to a server yet. '
'Please use the client to set up a sync conection.')
# INITIALIZE -------------------------------------------------------
def _initialize(self, *args, **kwargs):
......@@ -292,10 +298,19 @@ class MplFigClient(Figure):
print(SEVR + "The axes name ", name, " was not found")
return None
def get_axes_name(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
# SET RAW DATA -----------------------------------------------------
def set_rawdata(self, rawdata):
''' This function sets loacally the names of the remote data in a similar way as a local figure would do.
Warning : No consitancy checking is done. The server side will report the errors.
''' This function sets loacally the names of the remote data
in a similar way as a local figure would do.
Warning : No consitancy checking is done. The server
side will report the errors.
'''
self.remote_rawdata = rawdata
......@@ -306,16 +321,10 @@ class MplFigClient(Figure):
synchronized figure (server-side) """
if (self.client is not None) and (self.sync_id != -1):
# try:
if (True):
datas = self.client.sync_fig_format_rawdata(self.sync_id)
# except:
# print(SEVR+'The server-side figure could not format the data...')
# return(False)
for ax, data in zip(self.get_axes(), datas):
# each data is a string that can be unpacked by axes itself
# ax.data = ax.unpackFormattedData(data)
ax.data = data
else:
......
......@@ -41,10 +41,10 @@ class Grid(object):
def get_grids(self):
return(self.grids)
def contains_a_grid(self):
return(len(self.grids) > 0)
def set_position(self, pos):
left, bottom, width, height = pos
self.left = left
......@@ -59,30 +59,35 @@ class VerticalGrid(Grid):
nbr_axes = len(self.items)
if nbr_axes > 0:
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
new_bottom = self.margin + self.bottom + \
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)
Grid.layout(self)
Grid.layout(self)
class HorizontalGrid(Grid):
def layout(self):
nbr_axes = len(self.items)
if nbr_axes > 0:
axes_width = (self.width - (nbr_axes-1)*self.padding - 2.*self.margin)/nbr_axes
axes_width = (self.width - (nbr_axes-1)*self.padding -
2.*self.margin)/nbr_axes
for index in range(0, nbr_axes):
new_left = self.margin + self.left + index*axes_width + index*self.padding
new_bottom = self.margin + self.bottom
new_left = self.margin + self.left + \
index*axes_width + index*self.padding
new_bottom = self.margin + self.bottom
new_width = axes_width
new_height = self.height - 2.*self.margin
new_frame = [new_left, new_bottom, new_width, new_height]
self.items[index].set_position(new_frame)
Grid.layout(self)
Grid.layout(self)
......@@ -176,7 +176,7 @@ class MplHandler(SocketServer.StreamRequestHandler):
def handle(self):
print('HANDLING...')
print('Server handling request...')
reply = None
......@@ -187,6 +187,7 @@ class MplHandler(SocketServer.StreamRequestHandler):
try:
unpickler = MplUnpickler(self.rfile)
request = unpickler.load()
print('Server message loaded...')
if isinstance(request, Query):
if request.query_type == request.READDATA:
......@@ -217,14 +218,13 @@ class MplHandler(SocketServer.StreamRequestHandler):
elif isinstance(request, Answer):
# needed for server???
pass
elif isinstance(request, request):
self.serv_print('received unknown requestnal')
reply = Status(False, "received unknown requestnal")
elif isinstance(request, Signal):
self.serv_print('received unknown Signal')
reply = Status(False, "received unknown Signal")
else:
self.serv_print('what is happening here???'
' received Object of type:')
self.serv_print(str(request))
reply = Status(False, "received something totally diffenent")
self.serv_print('Server received unknown object:'
' of type:'+str(type(request)))
reply = Status(False, "Server received unknown object")
if isinstance(reply, Signal):
if debug:
......@@ -232,10 +232,14 @@ class MplHandler(SocketServer.StreamRequestHandler):
except EOFError:
print("could not unpickle, noting in the file")
except Exeption as e:
raise e
finally:
if reply:
pickle.dump(reply, self.wfile)
#~ else:
#~ pickle.dump(Status(False,None), self.wfile)
# these two lines are not needed
self.wfile.close()
......
......@@ -60,7 +60,7 @@ class Query(Signal):
class Status(Signal):
def __init__(self, value, error):
if (value == True) or (value == False):
if value in [True, False]:
self.value = value
else:
print('value parameter of a status signal'
......
......@@ -12,7 +12,8 @@ from clientside.figures_tests import FigTest as FigTestc
from serverside.figures_tests import FigTest2 as FigTests2
from clientside.figures_tests import FigTest2 as FigTestc2
SERVER_IOFUNCTIONS = {'read_stupid_data': read_stupid_data,'read_stupid_data_2': read_stupid_data_2}
SERVER_IOFUNCTIONS = {'read_stupid_data': read_stupid_data,
'read_stupid_data_2': read_stupid_data_2}
SERVER_FIGURES = {'FigTest': FigTests,'FigTest2': FigTests2}
import serverside.myplotlib as mpl_server
......@@ -33,16 +34,24 @@ class ComSetupTestCase(unittest.TestCase):
print('REQUEST CONNECTION...')
self.client.connect(('localhost', 12345))
print('CONNECTED')
self.assertEqual(self.client.connected,True)
self.assertTrue(self.client.connected)
# Send a signal without meaning to the server.
# A negative status message is expected as a repy
#~ client.send(Signal(True,'Hello World')) # Not working ATM
#~ resp = client.wait_for_signal()
#~ self.assertIsInstance(resp, Status)
#~ self.assertFalse(resp.value)
#~ self.assertEqual(type(resp.content),str)
print('REQUEST DISCONNECTION...')
self.client.disconnect()
self.assertFalse(self.client.connected)
print('DISCONNECTED')
def tearDown(self) :
self.server.server_close()
self.server.shutdown()
# Warning: If server and client are local the client can not shut down the port because the server has still a handle on it'''
# maybe this can be circumvented by setting up an external tunneling with ssh???
del self.server
del self.client
......@@ -52,9 +61,6 @@ class RemoteFigTestCase(unittest.TestCase):
self.server = mpl_server.MplServer(port=12347, known_functions=SERVER_IOFUNCTIONS, known_figures=SERVER_FIGURES)
self.client = mpl_client.MplClient()
self.client.host = 'localhost'
self.client.port = 12345
self.server.run(as_daemon=True)
self.client.connect(('localhost',12347))
......@@ -109,6 +115,7 @@ class RemoteFigTestCase(unittest.TestCase):
def test_re_sync(self):
fig1 = self.client.new_sync_figure(FigTestc, ('data1',))
fig1.de_sync_fig()
self.assertEqual(len(self.server._figures),0)
fig1.re_sync_fig()
def tearDown(self) :
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment