Salome HOME
*** empty log message ***
[tools/eficas.git] / Extensions / param2.py
1 # -*- coding: utf-8 -*-
2 from __future__ import division
3 import math
4 import types
5
6 try:
7   import Numeric
8 except:
9   import numpy
10   Numeric = numpy
11
12 def mkf(value):
13     if type(value) in (type(1), type(1L), type(1.5), type(1j),type("hh")) :
14         return Constant(value)
15     elif isinstance(value, Formula):
16         return value
17     elif type(value) == type([]):
18         return Constant(value)
19     else:
20 #        return Constant(value)
21         raise TypeError, ("Can't make formula from", value)
22
23 #class Formula(object):
24 class Formula:
25     def __len__(self):
26         val=self.eval()
27         if val is None:return 0
28         try:
29            return len(val)
30         except:
31            return 1
32     def __complex__(self): return complex(self.eval())
33     def __int__(self): return int(self.eval())
34     def __long__(self): return long(self.eval())
35     def __float__(self): return float(self.eval())
36     def __pos__(self): return self  # positive
37     def __neg__(self): return Unop('-', self)
38     def __abs__(self): return Unop('abs', self)
39     def __add__(self, other): return Binop('+', self, other)
40     def __radd__(self, other): return Binop('+', other, self)
41     def __sub__(self, other): return Binop('-', self, other)
42     def __rsub__(self, other): return Binop('-', other, self)
43     def __mul__(self, other): return Binop('*', self, other)
44     def __rmul__(self, other): return Binop('*', other, self)
45     def __div__(self, other): return Binop('/', self, other)
46     def __rdiv__(self, other): return Binop('/', other, self)
47     def __truediv__(self, other): return Binop('/', self, other)
48     def __rtruediv__(self, other): return Binop('/', other, self)
49     def __floordiv__(self, other): return Binop('//', self, other)
50     def __rfloordiv__(self, other): return Binop('//', other, self)
51     def __pow__(self, other): return Binop('**', self, other)
52     def __rpow__(self, other): return Binop('**', other, self)
53     def __getitem__(self,i):return Binop('[]',self,i)
54     def __cmp__( self, other ): return self.eval().__cmp__(other)
55     def __eq__(  self, other ): return self.eval() == other
56     def __ne__(  self, other ): return self.eval() != other
57     def __lt__(  self, other ): return self.eval() < other
58     def __le__(  self, other ): return self.eval() <= other
59     def __gt__(  self, other ): return self.eval() > other
60     def __ge__(  self, other ): return self.eval() >= other
61     def __hash__(self):return id(self)
62
63 def _div(a,b):
64   if isinstance(a,(int,long)) and isinstance(b,(int,long)):
65     if a%b:
66       return a/b
67     else:
68       return a//b
69   else:
70     return a/b
71
72
73 class Binop(Formula):
74     opmap = { '+': lambda a, b: a + b,
75               '*': lambda a, b: a * b,
76               '-': lambda a, b: a - b,
77               '/': _div,
78               '//': lambda a, b: a // b,
79               '**': lambda a, b: a ** b,
80               '[]': lambda a, b: a[b] ,
81             }
82     def __init__(self, op, value1, value2):
83         self.op = op
84         self.values = mkf(value1), mkf(value2)
85     def __str__(self):
86         if self.op == '[]':
87            return "%s[%s]" % (self.values[0], self.values[1])
88         else:
89            return "(%s %s %s)" % (self.values[0], self.op, self.values[1])
90     def __repr__(self):
91         if self.op == '[]':
92            return "%s[%s]" % (self.values[0], self.values[1])
93         else:
94            return "(%s %s %s)" % (self.values[0], self.op, self.values[1])
95     def eval(self):
96         result= self.opmap[self.op](self.values[0].eval(),
97                                    self.values[1].eval())
98         while isinstance(result,Formula):
99               result=result.eval()
100         return result
101     def __adapt__(self,validator):
102         return validator.adapt(self.eval())
103
104
105 class Unop(Formula):
106     opmap = { '-': lambda x: -x,
107               'abs': lambda x: abs(x),
108              }
109     def __init__(self, op, arg):
110         self._op = op
111         self._arg = mkf(arg)
112     def __str__(self):
113         return "%s(%s)" % (self._op, self._arg)
114     def __repr__(self):
115         return "%s(%s)" % (self._op, self._arg)
116     def eval(self):
117         return self.opmap[self._op](self._arg.eval())
118     def __adapt__(self,validator):
119         return validator.adapt(self.eval())
120
121 class Unop2(Unop):
122     def __init__(self, nom, op, arg):
123         self._nom = nom
124         self._op = op
125         self._arg=[]
126         for a in arg:
127            self._arg.append(mkf(a))
128     def __str__(self):
129         s="%s(" % self._nom
130         for a in self._arg:
131            s=s+str(a)+','
132         s=s+")"
133         return s
134     def __repr__(self):
135         s="%s(" % self._nom
136         for a in self._arg:
137            s=s+str(a)+','
138         s=s+")"
139         return s
140     def eval(self):
141         l=[]
142         for a in self._arg:
143           l.append(a.eval())
144         return self._op(*l)
145
146 class Constant(Formula):
147     def __init__(self, value): self._value = value
148     def eval(self): return self._value
149     def __str__(self): return str(self._value)
150     def __adapt__(self,validator):
151         return validator.adapt(self._value)
152
153 class Variable(Formula):
154     def __init__(self,name,value):
155         self._name=name
156         self._value=value
157     def eval(self): return self._value
158     def __repr__(self): return "Variable('%s',%s)" % (self._name, self._value)
159     def __str__(self): return self._name
160     def __adapt__(self,validator):
161         return validator.adapt(self._value)
162
163 def Eval(f):
164     if isinstance(f,Formula):
165         f=f.eval()
166     elif type(f) in (types.ListType, ):
167         f=[Eval(i) for i in f]
168     elif type(f) in (types.TupleType,):
169         f=tuple([Eval(i) for i in f])
170     return f
171
172
173 #surcharge de la fonction cos de Numeric pour les parametres
174 original_ncos=Numeric.cos
175 def cos(f): return Unop('ncos', f)
176 Unop.opmap['ncos']=lambda x: original_ncos(x)
177 Numeric.cos=cos
178
179 #surcharge de la fonction sin de Numeric pour les parametres
180 original_nsin=Numeric.sin
181 def sin(f): return Unop('nsin', f)
182 Unop.opmap['nsin']=lambda x: original_nsin(x)
183 Numeric.sin=sin
184
185 #surcharge de la fonction array de Numeric pour les parametres
186 original_narray=Numeric.array
187 def array(f,*tup,**args): 
188     """array de Numeric met en défaut la mécanique des parametres
189        on la supprime dans ce cas. Il faut que la valeur du parametre soit bien définie
190     """
191     return original_narray(Eval(f),*tup,**args)
192 Numeric.array=array
193
194 #surcharge de la fonction sin de math pour les parametres
195 original_sin=math.sin
196 def sin(f): return Unop('sin', f)
197 Unop.opmap['sin']=lambda x: original_sin(x)
198 math.sin=sin
199
200 #surcharge de la fonction cos de math pour les parametres
201 original_cos=math.cos
202 Unop.opmap['cos']=lambda x: original_cos(x)
203 def cos(f): return Unop('cos', f)
204 math.cos=cos
205
206 #surcharge de la fonction sqrt de math pour les parametres
207 original_sqrt=math.sqrt
208 def sqrt(f): return Unop('sqrt', f)
209 Unop.opmap['sqrt']=lambda x: original_sqrt(x)
210 math.sqrt=sqrt
211
212 #surcharge de la fonction ceil de math pour les parametres
213 original_ceil=math.ceil
214 Unop.opmap['ceil']=lambda x: original_ceil(x)
215 def ceil(f): return Unop('ceil', f)
216 math.ceil=ceil