Commit 0944fee7 authored by Guilhem Saurel's avatar Guilhem Saurel

python format

parent efd545ef
......@@ -3,20 +3,24 @@ Copyright (c) 2010 CNRS
Author: Florent Lamiraux
"""
import sys, DLFCN
flags = sys.getdlopenflags()
import sys
import DLFCN
import entity # noqa
import signal_base # noqa
# Import C++ symbols in a global scope
# This is necessary for signal compiled in different modules to be compatible
sys.setdlopenflags(DLFCN.RTLD_NOW|DLFCN.RTLD_GLOBAL)
from wrap import *
flags = sys.getdlopenflags()
sys.setdlopenflags(DLFCN.RTLD_NOW | DLFCN.RTLD_GLOBAL)
from wrap import * # noqa
# Recover previous flags
sys.setdlopenflags(flags)
import entity, signal_base
def plug (signalOut, signalIn) :
def plug(signalOut, signalIn):
"""
Plug an output signal into an input signal
"""
# get signals and entities
w_plug(signalOut.obj, signalIn.obj)
w_plug(signalOut.obj, signalIn.obj) # noqa
......@@ -16,95 +16,109 @@ class CommandPath(object):
to store entity commands. It has no members except those automatically
defined at run time (which should be CommandPath or functions).
"""
mother=None
def __getattr__(self,name):
privateName=name+'_obj'
mother = None
def __getattr__(self, name):
privateName = name + '_obj'
if privateName in self.__dict__:
obj=getattr(self,privateName)
obj.mother=self.mother
obj = getattr(self, privateName)
obj.mother = self.mother
return obj
return object.__getattr__(self,name)
return object.__getattr__(self, name)
def createCommandModule( target,name ):
def createGetter( name ):
def __( self ):
obj = getattr(self,name)
obj.mother=self
def createCommandModule(target, name):
def createGetter(name):
def __(self):
obj = getattr(self, name)
obj.mother = self
return obj
return __
privateName = name+'_obj'
setattr( target,privateName, CommandPath() )
module = getattr( target,privateName )
privateName = name + '_obj'
setattr(target, privateName, CommandPath())
if not isinstance(target, CommandPath):
setattr(target, name, property(createGetter(privateName)))
if not isinstance(target,CommandPath) :
setattr( target,name, property(createGetter(privateName)) )
class CommandLauncher(object):
"""
"""
mother=None
fun=None
def __init__(self,fun): self.fun=fun
def __call__(self,*arg):
return self.fun(self.mother,*arg)
def createCommandLauncher( target,name,fun ):
if isinstance(target,CommandPath) :
privateName = name+'_obj'
setattr( target,privateName, CommandLauncher(fun) )
mother = None
fun = None
def __init__(self, fun):
self.fun = fun
def __call__(self, *arg):
return self.fun(self.mother, *arg)
def createCommandLauncher(target, name, fun):
if isinstance(target, CommandPath):
privateName = name + '_obj'
setattr(target, privateName, CommandLauncher(fun))
else:
setattr( target,name,fun )
setattr(target, name, fun)
def setattrpath( target,path,attribute ):
def setattrpath(target, path, attribute):
"""
Create in target an new attribute with value path (available at
target.path1. ... .pathn).
"""
pathk=target
read=True
if type(path)==type(str()): path=path.split('.')
pathk = target
read = True
if isinstance(path, str):
path = path.split('.')
for tokenk in path[0:-1]:
if (not read) | (tokenk not in pathk.__dict__):
read=False
createCommandModule(pathk,tokenk)
pathk = getattr(pathk,tokenk+"_obj")
read = False
createCommandModule(pathk, tokenk)
pathk = getattr(pathk, tokenk + "_obj")
if callable(attribute):
createCommandLauncher( pathk,path[-1],attribute )
createCommandLauncher(pathk, path[-1], attribute)
else:
print("Should not happen")
setattr(pathk,path[-1],attribute )
setattr(pathk, path[-1], attribute)
def getattrpath( target,path ):
def getattrpath(target, path):
"""
Get in target the value located at path (available at
target.path1. ... .pathn).
"""
pathk=target
if type(path)==type(str()): path=path.split('.')
pathk = target
if isinstance(path, str):
path = path.split('.')
for tokenk in path:
privateName=tokenk+"_obj"
if (privateName in pathk.__dict__): pathk = getattr(pathk,privateName)
privateName = tokenk + "_obj"
if hasattr(pathk, privateName):
pathk = getattr(pathk, privateName)
else:
if ( tokenk in pathk.__dict__): pathk = getattr(pathk,tokenk)
if hasattr(pathk, tokenk):
pathk = getattr(pathk, tokenk)
else:
raise Exception('Path does not exist -- while accessing "'+tokenk+'" in '+'.'.join(path))
raise Exception('Path does not exist -- while accessing "' + tokenk + '" in ' + '.'.join(path))
return pathk
def existattrpath( target,path ):
def existattrpath(target, path):
"""
Check for the existence in target of a value located at path (available at
target.path1. ... .pathn).
"""
pathk=target
if type(path)==type(str()): path=path.split('.')
pathk = target
if isinstance(path, str):
path = path.split('.')
for tokenk in path[0:-1]:
print('check ',tokenk)
privateName=tokenk+"_obj"
print('check ', tokenk)
privateName = tokenk + "_obj"
if (privateName not in pathk.__dict__):
return False
pathk = getattr(pathk,privateName)
name=path[-1]
privateName=name+"_obj"
return (name in pathk.__dict__)|(privateName in pathk.__dict__)
pathk = getattr(pathk, privateName)
name = path[-1]
privateName = name + "_obj"
return (name in pathk.__dict__) | (privateName in pathk.__dict__)
This diff is collapsed.
......@@ -6,102 +6,99 @@
def pseudozero(prec):
"""
"""
Return a string with '0...' and enough space to fill prec cars.
"""
res='0...'
for i in range(2,prec):
res+=' '
return res
res = '0...'
for i in range(2, prec):
res += ' '
return res
class matlab:
prec=12
space=2
fullPrec=1e-5
def __init__( self,obj ):
try:
return self.matlabFromMatrix(obj)
except:
pass
try:
return self.matlabFromVector(obj)
except:
pass
self.resstr = str(obj)
class matlab:
prec = 12
space = 2
fullPrec = 1e-5
def __str__(self):
return self.resstr
def __init__(self, obj):
try:
return self.matlabFromMatrix(obj)
except Exception:
pass
try:
return self.matlabFromVector(obj)
except Exception:
pass
self.resstr = str(obj)
def matlabFromMatrix(self,A):
nr=len(A)
nc=len(A[0]);
fm='%.'+str(self.prec)+'f'
maxstr=0
mstr=(())
for v in A:
lnstr=()
for x in v:
if (abs(x)<self.fullPrec*self.fullPrec):
curr='0'
else:
if (abs(x)<self.fullPrec):
curr=pseudozero(self.prec)
else:
curr= ' '+(fm % x)
if( maxstr<len(curr)):
maxstr=len(curr)
lnstr+=(curr,)
mstr+=(lnstr,)
def __str__(self):
return self.resstr
maxstr+=self.space
resstr='[...\n'
first=True
for v in mstr:
if first:
first=False;
else:
resstr+=' ;\n'
firstC=True
for x in v:
if firstC:
firstC=False
else:
resstr+=','
for i in range(1,maxstr-len(x)):
resstr+=' '
resstr+=x
resstr+=' ];'
self.resstr = resstr
def matlabFromMatrix(self, A):
fm = '%.' + str(self.prec) + 'f'
maxstr = 0
mstr = (())
for v in A:
lnstr = ()
for x in v:
if (abs(x) < self.fullPrec * self.fullPrec):
curr = '0'
else:
if (abs(x) < self.fullPrec):
curr = pseudozero(self.prec)
else:
curr = ' ' + (fm % x)
if (maxstr < len(curr)):
maxstr = len(curr)
lnstr += (curr, )
mstr += (lnstr, )
maxstr += self.space
resstr = '[...\n'
first = True
for v in mstr:
if first:
first = False
else:
resstr += ' ;\n'
firstC = True
for x in v:
if firstC:
firstC = False
else:
resstr += ','
for i in range(1, maxstr - len(x)):
resstr += ' '
resstr += x
resstr += ' ];'
self.resstr = resstr
def matlabFromVector(self,v):
nr=len(v)
fm='%.'+str(self.prec)+'f'
maxstr=0
vstr=(())
for x in v:
if (abs(x)<self.fullPrec*self.fullPrec):
curr='0'
else:
if (abs(x)<self.fullPrec):
curr=pseudozero(self.prec)
def matlabFromVector(self, v):
fm = '%.' + str(self.prec) + 'f'
maxstr = 0
vstr = (())
for x in v:
if (abs(x) < self.fullPrec * self.fullPrec):
curr = '0'
else:
curr= ' '+(fm % x)
if( maxstr<len(curr)):
maxstr=len(curr)
vstr+=(curr,)
if (abs(x) < self.fullPrec):
curr = pseudozero(self.prec)
else:
curr = ' ' + (fm % x)
if (maxstr < len(curr)):
maxstr = len(curr)
vstr += (curr, )
maxstr+=self.space
resstr='[ '
first=True
for x in vstr:
if first:
first=False;
else:
resstr+=','
for i in range(1,maxstr-len(x)):
resstr+=' '
resstr+=x
resstr+=' ]\';'
self.resstr = resstr
maxstr += self.space
resstr = '[ '
first = True
for x in vstr:
if first:
first = False
else:
resstr += ','
for i in range(1, maxstr - len(x)):
resstr += ' '
resstr += x
resstr += ' ]\';'
self.resstr = resstr
......@@ -8,17 +8,21 @@
# entity -> same as print(entity)
# change the prompt to be '%'
# Changing prompt
import sys
from dynamic_graph.signal_base import *
from dynamic_graph.entity import *
from dynamic_graph.entity import Entity
from dynamic_graph.signal_base import SignalBase
from matlab import matlab
# Enables shortcut "name"
def sig_short_name(self):
return self.getName().split(':')[-1]
setattr(SignalBase,'name',property(sig_short_name))
setattr(SignalBase, 'name', property(sig_short_name))
# Enables shortcuts "m"
# This code implements a pseudo function 'm' in the class signal_base,
......@@ -28,40 +32,53 @@ setattr(SignalBase,'name',property(sig_short_name))
# - sig.m +time: recompute at <time> after current time, and display.
class PrettySignalPrint:
sig = None
def __init__(self,sig):
def __init__(self, sig):
self.sig = sig
def __str__(self):
return self.sig.name+" = "+str(matlab(self.sig.value))
return self.sig.name + " = " + str(matlab(self.sig.value))
def __repr__(self):
return str(self)
def __call__(self,iter):
def __call__(self, iter):
self.sig.recompute(iter)
return self
def __add__(self,iter):
self.sig.recompute( self.sig.time+iter )
def __add__(self, iter):
self.sig.recompute(self.sig.time + iter)
return self
def sigMatPrint(sig):
return PrettySignalPrint(sig)
setattr(SignalBase,'m',property(PrettySignalPrint))
#print('Pretty matlab print set')
setattr(SignalBase, 'm', property(PrettySignalPrint))
# print('Pretty matlab print set')
# Enable the same as 'm', but directly on the signal object.
def sigRepr( self ):
return self.name+' = '+str(matlab(self.value))
def sigRepr(self):
return self.name + ' = ' + str(matlab(self.value))
def sigCall( sig,iter ):
def sigCall(sig, iter):
sig.recompute(iter)
print(sigRepr(sig))
def sigTimeIncr( sig,iter ):
sig.recompute(sig.time+iter)
def sigTimeIncr(sig, iter):
sig.recompute(sig.time + iter)
print(sigRepr(sig))
setattr(SignalBase,'__repr__',sigRepr)
setattr(SignalBase,'__call__',sigCall)
setattr(SignalBase,'__add__',sigTimeIncr)
setattr(SignalBase, '__repr__', sigRepr)
setattr(SignalBase, '__call__', sigCall)
setattr(SignalBase, '__add__', sigTimeIncr)
# Enables shortcut "deps"
# Implements the peudo function 'deps', that can be called without arg,
......@@ -69,31 +86,40 @@ setattr(SignalBase,'__add__',sigTimeIncr)
class SignalDepPrint:
defaultDepth = 2
sig = None
def __init__(self,sig):
self.sig=sig
def __init__(self, sig):
self.sig = sig
def __repr__(self):
return self.sig.displayDependencies(self.defaultDepth)
def __call__(self,depth):
def __call__(self, depth):
self.defaultDepth = depth
return self
setattr(SignalBase,'deps',property(SignalDepPrint))
setattr(Entity,'sigs',property(Entity.displaySignals))
setattr(Entity,'__repr__',Entity.__str__)
setattr(SignalBase, 'deps', property(SignalDepPrint))
setattr(Entity, 'sigs', property(Entity.displaySignals))
setattr(Entity, '__repr__', Entity.__str__)
# Changing prompt
import sys
sys.ps1 = '% '
# Enable function that can be call without()def optionalparentheses(f):
def optionalparentheses(f):
class decoclass:
def __init__(self,f): self.functor=f
def __init__(self, f):
self.functor = f
def __repr__(self):
res=self.functor()
if isinstance(res,str): return res
else: return ''
def __call__(self,*arg):
res = self.functor()
if isinstance(res, str):
return res
else:
return ''
def __call__(self, *arg):
return self.functor(*arg)
return decoclass(f)
......@@ -3,17 +3,18 @@
Author: Florent Lamiraux
"""
import wrap
import entity
import re
import collections
def stringToTuple (vector) :
import entity
import wrap
def stringToTuple(vector):
"""
Transform a string of format '[n](x_1,x_2,...,x_n)' into a tuple of numbers.
"""
# Find vector length
a = re.match('\[(\d+)\]',vector)
a = re.match(r'\[(\d+)\]', vector)
size = int(a.group(1))
# remove '[n]' prefix
vector = vector[len(a.group(0)):]
......@@ -23,75 +24,72 @@ def stringToTuple (vector) :
vector = vector.split(',')
# check size
if len(vector) != size:
raise TypeError('displayed size ' +
str(size) + ' of vector does not fit actual size: '
+ str(len(vector)))
raise TypeError('displayed size ' + str(size) + ' of vector does not fit actual size: ' + str(len(vector)))
res = map(float, vector)
return tuple (res)
return tuple(res)
def tupleToString (vector) :
def tupleToString(vector):
"""
Transform a tuple of numbers into a string of format
'[n](x_1, x_2, ..., x_n)'
"""
string = '[%d]('%len (vector)
string = '[%d](' % len(vector)
for x in vector[:-1]:
string += '%f,'%x
string += '%f)'%vector[-1]
string += '%f,' % x
string += '%f)' % vector[-1]
return string
def stringToMatrix (string) :
def stringToMatrix(string):
"""
Transform a string of format
'[n,m]((x_11,x_12,...,x_1m),...,(x_n1,x_n2,...,x_nm))' into a tuple
of tuple of numbers.
"""
# Find matrix size
a = re.search ('\[(\d+),(\d+)]', string)
nRows = int (a.group(1))
nCols = int (a.group(2))
a = re.search(r'\[(\d+),(\d+)]', string)
nRows = int(a.group(1))
nCols = int(a.group(2))
# Remove '[n,m]' prefix
string = string[len(a.group(0)):]
rows = string.split('),(')
if len(rows) != nRows:
raise TypeError('displayed nb rows ' +
nRows + ' of matrix does not fit actual nb rows: '
+ str(len(rows)))
raise TypeError('displayed nb rows ' + nRows + ' of matrix does not fit actual nb rows: ' + str(len(rows)))
m = []
for rstr in rows:
rstr = rstr.lstrip('(').rstrip(')\n')
r = map(float, rstr.split(','))
if len(r) != nCols:
raise TypeError('one row length ' +
len(r) +
' of matrix does not fit displayed nb cols: ' +
nCols)
raise TypeError('one row length ' + len(r) + ' of matrix does not fit displayed nb cols: ' + nCols)
m.append(tuple(r))
return tuple (m)
return tuple(m)
def matrixToString(matrix) :
def matrixToString(matrix):
"""
Transform a tuple of tuple of numbers into a string of format
'[n,m]((x_11,x_12,...,x_1m),...,(x_n1,x_n2,...,x_nm))'.
"""
nRows = len(matrix)
if nRows is 0 :
if nRows == 0:
return '[0,0](())'
nCols = len(matrix[0])
string = '[%d,%d](' % (nRows, nCols)
for r in range (nRows) :
for r in range(nRows):
string += '('
for c in range (nCols) :
string += str (float (matrix [r][c]))
if c != nCols-1 :
for c in range(nCols):
string += str(float(matrix[r][c]))
if c != nCols - 1:
string += ','
string += ')'
if r != nRows -1 :
if r != nRows - 1:
string += ','
string += ')'
return string
def objectToString(obj) :
def objectToString(obj):
"""
Transform an object to a string. Object is either
- an entity (more precisely a sub-class named Feature)
......@@ -101,23 +99,24 @@ def objectToString(obj) :
- an integer,
- a boolean,
"""
if (hasattr (obj, "__iter__")) :
if (hasattr(obj, "__iter__")):
# matrix or vector
if len(obj) is 0 :
if len(obj) == 0:
return ""
else :
if (hasattr(obj[0], "__iter__")) :
#matrix
else:
if (hasattr(obj[0], "__iter__")):
# matrix
return matrixToString(obj)
else :
#vector
else:
# vector
return tupleToString(obj)
elif isinstance(obj, entity.Entity) :
elif isinstance(obj, entity.Entity):
return obj.name
else :
else:
return str(obj)
def stringToObject(string) :
def stringToObject(string):
"""
Convert a string into one of the following types
- a matrix (tuple of tuple),
......@@ -127,57 +126,60 @@ def stringToObject(string) :
Successively attempts conversion in the above order and return
on success. If no conversion fits, the string is returned.
"""
if isinstance(string,float): return string
if isinstance(string,int): return string
if isinstance(string,tuple): return string
try :
if isinstance(string, float):
return string
if isinstance(string, int):
return string
if isinstance(string, tuple):
return string