Commit f2522448 authored by Philipp Gast's avatar Philipp Gast
Browse files

started to become pep8 conformant. added a specific test for this purpose.

parent ccada0af
Pipeline #482 failed with stage
in 5 minutes and 26 seconds
......@@ -35,3 +35,10 @@ myplotlib_import_network_latex_tkagg:
- python test_com_nogl.py
- python -m tests
- ./clean_test_folder.sh
myplotlib_test_pep8:
script:
- git name-rev --name-only HEAD
- ls -l
- python -m comp_pep8
allow_failure: true
......@@ -38,11 +38,13 @@ from .config import D_HIERARCHY
import os as os
import numpy as np
np.set_printoptions(threshold='nan')
from signal import Signal, Query, Status, Answer
from mpl_unpickler import MplUnpickler
np.set_printoptions(threshold='nan')
# matplotlib import for client/local -----------------------------------
if D_HIERARCHY in ('CLIENT', 'client', 'LOCAL', 'local'):
......@@ -50,12 +52,16 @@ if D_HIERARCHY in ('CLIENT', 'client', 'LOCAL', 'local'):
print(INFO+'Import '+__package__+' as a client.')
else:
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
......@@ -64,22 +70,23 @@ 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
from matplotlib.figure import FigureType name of new folder
from matplotlib import is_interactive
from matplotlib import use
from .config import D_HOST, D_PORT
from socket import socket, AF_INET, SOCK_STREAM
elif D_HIERARCHY in ('SERVER', 'server'):
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:
else:
print(SEVR+'the value of D_HIERARCHY has to be SERVER or CLIENT')
raise ImportError
# myplotlib
from .myData import MyData
......@@ -91,11 +98,11 @@ from .config import D_OPATH, D_OFORMAT
from .config import D_DEBUG
if D_HIERARCHY in ('CLIENT', 'client', 'LOCAL', 'local'):
from .rconfig import rcParams
if D_HIERARCHY in ('CLIENT', 'client'):
# MyAxes: Overlay on matplotlib.Axes class
from .myAxes_client import MyAxes_client as MyAxes
......@@ -103,8 +110,7 @@ if D_HIERARCHY in ('CLIENT', 'client'):
from .myFig_client import MyFig_client as MyFig
from .progressbar import ProgressBar
from .mplClient import MplClient
from .mplClient2 import MplClient2
elif(D_HIERARCHY in ('SERVER', 'server')):
......@@ -129,7 +135,6 @@ elif(D_HIERARCHY in ('SERVER', 'server')):
#'FigTest': FigTest
}
from .mplServer import MplServer
from .mplServer2 import MplServer2, MplHandler
elif D_HIERARCHY in ('LOCAL', 'local'):
......@@ -146,15 +151,15 @@ elif D_HIERARCHY in ('LOCAL', 'local'):
from .empty_axes import EmptyAxes
else:
print(SEVR+'the value of D_HIERARCHY has to be SERVER, CLIENT or LOCAL')
raise ImportError
raise ImportError
if D_HIERARCHY in ('CLIENT', 'client', 'LOCAL', 'local'):
_G_WINDOWS = []
# MyWin: Overlay on matplotlib.FigureManager class
if rcParams['backend'] == u'TkAgg':
from .myWin_TkAgg import MyWin_TkAgg as MyWin
......@@ -167,7 +172,8 @@ 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 supported interactive mode not available")
print(SEVR + """The backend you choosed is not
supported interactive mode not available""")
# myTool.*: interface functions to use myplotlib interactively
......
......@@ -35,8 +35,8 @@ from . import D_HIERARCHY
from . import INFO, SPCE, DBUG
if D_HIERARCHY in ('CLIENT', 'client', 'local', 'LOCAL'):
from . import myTest, testList
from .test import __dict__ as availTests
from . import myTest
from .test import __dict__ as avail_tests
else:
from socket import socket, AF_INET, SOCK_STREAM
from . import D_HOST, D_PORT
......@@ -48,9 +48,9 @@ import getopt
run4Plot = False
arg4Plot = ''
run4Test = False
debug = False
debug = False
# GET PASSED OPTIONS ---------------------------------------------------
# GET PASSED OPTIONS ---------------------------------------------------
usage = '''
{0}Usage: python mfdPlot [-h]
{1} [-t/--test [all/<num of test>]
......@@ -63,7 +63,7 @@ usage = '''
try:
opts, args = getopt.getopt(
sys.argv[1:], "htp:", ["test=", "plot=", "args=", "debug", "server"])
except getopt.GetoptError:
print(usage)
sys.exit(1)
......@@ -73,26 +73,26 @@ for opt, arg in opts:
if(opt == '-h'):
print(usage)
sys.exit(0)
elif opt in ("-t"):
run4Test = True
elif opt in ("--test"):
run4Test = True
tests = arg.split(', ')
testList = []
for test in tests:
if test in availTests.keys():
testList.append(availTests[test])
if test in avail_tests.keys():
testList.append(avail_tests[test])
if len(testList) == 0:
print(" > sevr-: you need to give valid tests to be tested.")
exit(1)
elif opt in ("-p", "--plot"):
run4Plot = True
arg4Plot = str(arg)
elif opt in ("--debug"):
debug = True
......@@ -107,7 +107,7 @@ if run4Test:
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))
fail = []
status = True
......@@ -120,9 +120,9 @@ if run4Test:
print(INFO + 72 * '-' + " [PASSED]")
else:
print(INFO + 72 * '-' + " [FAILED] !")
status = status and testStatus
# Print final status
print('\n')
print(INFO + 'Status of test series: ' + str(status))
......@@ -134,9 +134,9 @@ if run4Test:
# SECTION: PLOTS ------------------------------------------------------
elif run4Plot:
print(INFO + '{title:{c}^{n}}'.format(title=' Run for Plot ', c='=', n=72))
# try:
# data = arg4Plot
# somePlottingRoutine(data)
......@@ -150,7 +150,7 @@ elif run4server:
from . import Server
from . import readStupidData
server = Server()
server.init()
server.run()
......@@ -158,5 +158,3 @@ elif run4server:
else:
print(usage)
......@@ -10,22 +10,22 @@ SPCE = " > -----: "
# CONFIGURATION --------------------------------------------------------
# myFig
D_FIGNUM = 0 # default figure number
D_FIGSIZE = (8., 6.) # default figure size
D_REFORMAT = True # default reformat value
D_FORMATTED = False # default formatted value
D_RAWDATA = MyData() # default raw data
D_INPUTARG = 'current' # default Input argument
D_FIGNUM = 0 # default figure number
D_FIGSIZE = (8., 6.) # default figure size
D_REFORMAT = True # default reformat value
D_FORMATTED = False # default formatted value
D_RAWDATA = MyData() # default raw data
D_INPUTARG = 'current' # default Input argument
# myIOs
D_IPATH = '../' # default path to project
D_IPATH = '../' # default path to project
# print2file
D_OPATH = 'myplotlib/img/' # default path to ouput
D_OFORMAT = 'png' # default format for ouput
D_OPATH = 'myplotlib/img/' # default path to ouput
D_OFORMAT = 'png' # default format for ouput
# Debug
D_DEBUG = True # default debug value
D_DEBUG = True # default debug value
# PLOTTING CONFIGURATION -----------------------------------------------
# BACKEND: u'TKAgg', u'GTKAgg', u'WXAgg', u'Qt4Agg', u'MacOSX'
......@@ -36,7 +36,7 @@ rcParams['font.family'] = 'serif'
rcParams['font.size'] = '22'
try:
rcParams['text.usetex'] = True # need dvipng, ghostscript, and Agg
except:
except Exception:
print(WARN + "I could not set the LaTeX font sorry...")
# LINES
......@@ -61,7 +61,7 @@ try:
rcParams['ytick.minor.width'] = 1.5
rcParams['xtick.minor.visible'] = False
rcParams['ytick.minor.visible'] = False
except:
except Exception:
pass
# DPI
......
......@@ -15,19 +15,19 @@ SPCE = " > -----: "
# CONFIGURATION --------------------------------------------------------
# myFig
D_FIGNUM = 0 # default figure number
D_FIGSIZE = (8., 6.) # default figure size
D_REFORMAT = True # default reformat value
D_FORMATTED = False # default formatted value
D_RAWDATA = MyData() # default raw data
D_INPUTARG = 'current' # default Input argument
D_FIGNUM = 0 # default figure number
D_FIGSIZE = (8., 6.) # default figure size
D_REFORMAT = True # default reformat value
D_FORMATTED = False # default formatted value
D_RAWDATA = MyData() # default raw data
D_INPUTARG = 'current' # default Input argument
# myIOs
D_IPATH = '../' # default path to project
D_IPATH = '../' # default path to project
# print2file
D_OPATH = 'myplotlib/img/' # default path to ouput
D_OFORMAT = 'png' # default format for ouput
D_OPATH = 'myplotlib/img/' # default path to ouput
D_OFORMAT = 'png' # default format for ouput
# Debug
D_DEBUG = True # default debug value
D_DEBUG = True # default debug value
from myplotlib import MyAxes
class EmptyAxes(MyAxes):
def plotting(self):
return(True)
def formatRawData(self, rawdata):
def format_raw_data(self, rawdata):
self.data = rawdata.data
return(True)
from myplotlib import MyFig
class EmptyFig(MyFig):
def __init__(self, **kwargs):
MyFig.__init__(self, (), **kwargs)
def addAxes(self):
def add_axes(self):
pass
from . import socket, AF_INET, SOCK_STREAM
from . import INFO, DBUG, WARN, SEVR, SPCE
SIZE_STATUS_MAX = 1024
from . import ProgressBar
from . import D_DEBUG
DEBUG = D_DEBUG
# CLASS CLIENT ---------------------------------------------------------
class MplClient(object):
# CONSTRUCTOR ------------------------------------------------------
def __init__(self, ip, port):
'''This is a myplotlib client.
It sends instructions to a MplSever at host:port.
'''
self.ip = ip
self.port = port
# just a list of names
#~ self.currentRemoteData = []
# PACK SIGNAL ------------------------------------------------------
def packSignal(self, unpackedSignal):
'''Pack the signal.'''
packedSignal = ''
header, instrucSize = unpackedSignal
header = str(header)
instrucSize = str(instrucSize)
packedSignal = "("+"\""+header+"\""+", "+instrucSize+")"
return(packedSignal)
# PACK INSTRUCTION -------------------------------------------------
def packInstructions(self, instructions):
'''Pack the instructions, a tuple of strings: (header, content).'''
header, packedContent = instructions
packedInstructions = "(\""+header+"\", "+str(packedContent)+")"
return(packedInstructions)
# PACK READDATA CONTENT --------------------------------------------
def packReadDataContent(self, ioFunction, dataName, *args, **kwargs):
'''Pack the content of the instructions for readData.'''
packedContent = "['"+str(dataName)+"', '"+ioFunction.__name__+"', "+str(args)+", "+str(kwargs)+"]"
return(packedContent)
# READ DATA --------------------------------------------------------
def readData(self, ioFunction, dataName, *args, **kwargs):
'''Start the readData procedure.
1. Send ReadData Signal with length of packedInstructions
2. Wait for receipt
3. Send Instructions
4. Wait for status
'''
# Pack instructions and get size
content = self.packReadDataContent(ioFunction, dataName, *args, **kwargs)
packedInstructions = self.packInstructions(('readData', content))
instructionSize = len(packedInstructions)
# Send the signal with size
signal = self.packSignal(('readData', instructionSize))
sock = self.sendSignal(signal)
if(DEBUG):
print(INFO+'Sent Signal, waiting for receipt...')
status = self.waitForReceipt(sock)
# Check status
if not status:
return(False)
if(DEBUG):
print(INFO+'Received the receipt')
print(INFO+'Sent the instructions, waiting for status: ')
# Send Instructions
self.sendInstructions(sock, packedInstructions)
# Check status
status = self.waitForStatus(sock)
if not status:
return(False)
return(True)
# SEND SIGNAL ------------------------------------------------------
def sendSignal(self, packedSignal):
'''Send a signal: readData, newSyncFigure, syncFigFormatRawData'''
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((self.ip, self.port))
sock.sendall(str(packedSignal))
return(sock)
# WAIT FOR RECEIPT -------------------------------------------------
def waitForReceipt(self, sock):
'''Wait for the receipt. return a tuple.'''
answer = sock.recv(SIZE_STATUS_MAX)
status = False
errmsg = ''
header = ''
try:
header, status, errmsg = eval(answer)
except:
print(SEVR+'could not Exctract the receipt.')
print(SEVR+'Received: '+str(answer))
status = eval(status)
if not status:
print(SEVR+"SERVER: "+str(errmsg))
return(status)
# SEND INSTRUCTIONS ------------------------------------------------
def sendInstructions(self, sock, packedInstructions):
'''Send Instructions.'''
sock.sendall(packedInstructions)
return(True)
# SEND ALT INSTRUCTIONS --------------------------------------------
# def sendInstructions(self, packedInstructions):
# '''Send Instructions.'''
# sock = socket(AF_INET, SOCK_STREAM)
# sock.connect((self.ip, self.port))
# sock.sendall(packedInstructions)
#
# return(sock)
# WAIT FOR STATUS --------------------------------------------------
def waitForStatus(self, sock):
'''Wait for the status. return a tuple.'''
answer = sock.recv(SIZE_STATUS_MAX)
status = False
errmsg = ''
header = ''
try:
header, status, errmsg = eval(answer)
except:
print(SEVR+'could not Exctract the status.')
status = eval(status)
if not status:
print(SEVR+"SERVER: "+str(errmsg))
return(status)
# NEW SYNC FIGURE --------------------------------------------------
def newSyncFigure(self, figClass, symbolicRawdata, **kwargs):
'''Start the readData procedure.
1. Send newSyncFigure Signal with length of packedInstructions
2. Wait for receipt
3. Send Instructions
4. Wait for status
'''
# create temporary syncFigure
syncFigure = figClass(symbolicRawdata, **kwargs)
# Pack instructions and get size
content = self.packNewSyncFigureContent(figClass, symbolicRawdata, **kwargs)
packedInstructions = self.packInstructions(('newSyncFigure', content))
instructionSize = len(packedInstructions)
# Send the signal with size
signal = self.packSignal(('newSyncFigure', instructionSize))
sock = self.sendSignal(signal)
if(DEBUG):
print(INFO+'Sent Signal, waiting for receipt...')
# Wait for the receipt
status = self.waitForReceipt(sock)
# Check status
if not status:
del(syncFigure)
return(None)
if(DEBUG):
print(INFO+'Received the receipt')
print(INFO+'Sent the instructions, waiting for status: ')
# Send Instructions
self.sendInstructions(sock, packedInstructions)
# Check status
ID = self.waitForStatus(sock)
# If failed
if not ID:
del(syncFigure)
return(None)
# If created
else:
# Link the temporary Sync Figure
syncFigure.syncID = ID
syncFigure.client = self
return(syncFigure)
# PACK NEW SYNC FIGURE CONTENT -------------------------------------
def packNewSyncFigureContent(self, FigClass, rawdata, **kwargs):
'''Pack the content of the instructions for new Sync Figure.'''
packedContent = "['"+FigClass.__name__+"', "+str(rawdata)+", "+str(kwargs)+"]"
return(packedContent)
# SYNC FIGURE FORMAT RAWDATA ---------------------------------------
def syncFigFormatRawData(self, syncID):
'''the returned datas should be a tuple of strings'''
# Send the signal with syncID
signal = self.packSignal(('syncFigFormatRawData', "'"+syncID+"'"))
sock = self.sendSignal(signal)
if(DEBUG):
print(INFO+'Sent Signal, waiting for the size of the formatted data...')
# Wait for the size of the formatted data
dataSize = self.waitForStatus(sock)
# if failed
if not dataSize:
self.sendCloseConnection(sock)
return(None)
# Send a receipt
self.sendReceipt(sock)
print('CLIENT: I received a data size of: '+str(dataSize))
# Wait for the formatted data
packedData = self.waitForData(sock, dataSize)
# print(INFO+str(packedData))
# Unpack
header, datas, errmsg = self.unpackFormattedData(packedData)
# Check status
if datas is not None:
if(DEBUG):
print(INFO+'Received the data')
else:
print(WARN + 'The server could not format the rawdata.')
print(errmsg)
datas = (None,)
return(datas)
# SEND CLOSE CONNECTION --------------------------------------------
def sendCloseConnection(self, sock):
'''Send a close connection receipt to the server.'''
packedReceipt = self.packAnswer(('', "'False'", 'Close connection'))
sock.sendall(packedReceipt)
return(True)
# SEND RECEIPT -----------------------------------------------------
def sendReceipt(self, sock):
'''Send a receipt to the server.'''