]> SALOME platform Git repositories - tools/eficas.git/blob - Extensions/param2.py
Salome HOME
90b74af81b47de31c6c8783678cce51c2d0cfb71
[tools/eficas.git] / Extensions / param2.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2007-2013   EDF R&D
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20 from __future__ import division
21 import math
22 import types
23
24 try:
25   import Numeric
26 except:
27   import numpy
28   Numeric = numpy
29
30 def mkf(value):
31     if type(value) in (type(1), type(1L), type(1.5), type(1j),type("hh")) :
32         return Constant(value)
33     elif isinstance(value, Formula):
34         return value
35     elif type(value) == type([]):
36         return Constant(value)
37     else:
38 #        return Constant(value)
39         raise TypeError, ("Can't make formula from", value)
40
41 #class Formula(object):
42 class Formula:
43     def __len__(self):
44         val=self.eval()
45         if val is None:return 0
46         try:
47            return len(val)
48         except:
49            return 1
50     def __complex__(self): return complex(self.eval())
51     def __int__(self): return int(self.eval())
52     def __long__(self): return long(self.eval())
53     def __float__(self): return float(self.eval())
54     def __pos__(self): return self  # positive
55     def __neg__(self): return Unop('-', self)
56     def __abs__(self): return Unop('abs', self)
57     def __add__(self, other): return Binop('+', self, other)
58     def __radd__(self, other): return Binop('+', other, self)
59     def __sub__(self, other): return Binop('-', self, other)
60     def __rsub__(self, other): return Binop('-', other, self)
61     def __mul__(self, other): return Binop('*', self, other)
62     def __rmul__(self, other): return Binop('*', other, self)
63     def __div__(self, other): return Binop('/', self, other)
64     def __rdiv__(self, other): return Binop('/', other, self)
65     def __truediv__(self, other): return Binop('/', self, other)
66     def __rtruediv__(self, other): return Binop('/', other, self)
67     def __floordiv__(self, other): return Binop('//', self, other)
68     def __rfloordiv__(self, other): return Binop('//', other, self)
69     def __pow__(self, other): return Binop('**', self, other)
70     def __rpow__(self, other): return Binop('**', other, self)
71     def __getitem__(self,i): 
72         if i > len(self) : raise StopIteration
73         return Binop('[]',self,i)
74     def __cmp__( self, other ): return self.eval().__cmp__(other)
75     def __eq__(  self, other ): return self.eval() == other
76     def __ne__(  self, other ): return self.eval() != other
77     def __lt__(  self, other ): return self.eval() < other
78     def __le__(  self, other ): return self.eval() <= other
79     def __gt__(  self, other ): return self.eval() > other
80     def __ge__(  self, other ): return self.eval() >= other
81     def __hash__(self):return id(self)
82
83 def _div(a,b):
84   if isinstance(a,(int,long)) and isinstance(b,(int,long)):
85     if a%b:
86       return a/b
87     else:
88       return a//b
89   else:
90     return a/b
91
92
93 class Binop(Formula):
94     opmap = { '+': lambda a, b: a + b,
95               '*': lambda a, b: a * b,
96               '-': lambda a, b: a - b,
97               '/': _div,
98               '//': lambda a, b: a // b,
99               '**': lambda a, b: a ** b,
100               '[]': lambda a, b: a[b] ,
101             }
102     def __init__(self, op, value1, value2):
103         self.op = op
104         self.values = mkf(value1), mkf(value2)
105
106     def __str__(self):
107         if self.op == '[]':
108            return "%s[%s]" % (self.values[0], self.values[1])
109         else:
110            return "(%s %s %s)" % (self.values[0], self.op, self.values[1])
111     def __repr__(self):
112         if self.op == '[]':
113            return "%s[%s]" % (self.values[0], self.values[1])
114         else:
115            return "(%s %s %s)" % (self.values[0], self.op, self.values[1])
116     def eval(self):
117         result= self.opmap[self.op](self.values[0].eval(),
118                                    self.values[1].eval())
119         while isinstance(result,Formula):
120               result=result.eval()
121         return result
122     def __adapt__(self,validator):
123         return validator.adapt(self.eval())
124
125
126 class Unop(Formula):
127     opmap = { '-': lambda x: -x,
128               'abs': lambda x: abs(x),
129              }
130     def __init__(self, op, arg):
131         self._op = op
132         self._arg = mkf(arg)
133     def __str__(self):
134         return "%s(%s)" % (self._op, self._arg)
135     def __repr__(self):
136         return "%s(%s)" % (self._op, self._arg)
137     def eval(self):
138         return self.opmap[self._op](self._arg.eval())
139     def __adapt__(self,validator):
140         return validator.adapt(self.eval())
141
142 class Unop2(Unop):
143     def __init__(self, nom, op, arg):
144         self._nom = nom
145         self._op = op
146         self._arg=[]
147         for a in arg:
148            self._arg.append(mkf(a))
149     def __str__(self):
150         s="%s(" % self._nom
151         for a in self._arg:
152            s=s+str(a)+','
153         s=s+")"
154         return s
155     def __repr__(self):
156         s="%s(" % self._nom
157         for a in self._arg:
158            s=s+str(a)+','
159         s=s+")"
160         return s
161     def eval(self):
162         l=[]
163         for a in self._arg:
164           l.append(a.eval())
165         return self._op(*l)
166
167 class Constant(Formula):
168     def __init__(self, value): self._value = value
169     def eval(self): return self._value
170     def __str__(self): return str(self._value)
171     def __adapt__(self,validator):
172         return validator.adapt(self._value)
173
174 class Variable(Formula):
175     def __init__(self,name,value):
176         self._name=name
177         self._value=value
178     def eval(self): return self._value
179     def __repr__(self): return "Variable('%s',%s)" % (self._name, self._value)
180     def __str__(self): return self._name
181     def __adapt__(self,validator):
182         return validator.adapt(self._value)
183
184 def Eval(f):
185     if isinstance(f,Formula):
186         f=f.eval()
187     elif type(f) in (types.ListType, ):
188         f=[Eval(i) for i in f]
189     elif type(f) in (types.TupleType,):
190         f=tuple([Eval(i) for i in f])
191     return f
192
193
194 #surcharge de la fonction cos de Numeric pour les parametres
195 original_ncos=Numeric.cos
196 def cos(f): return Unop('ncos', f)
197 Unop.opmap['ncos']=lambda x: original_ncos(x)
198 Numeric.cos=cos
199
200 #surcharge de la fonction sin de Numeric pour les parametres
201 original_nsin=Numeric.sin
202 def sin(f): return Unop('nsin', f)
203 Unop.opmap['nsin']=lambda x: original_nsin(x)
204 Numeric.sin=sin
205
206 #surcharge de la fonction array de Numeric pour les parametres
207 original_narray=Numeric.array
208 def array(f,*tup,**args): 
209     """array de Numeric met en défaut la mécanique des parametres
210        on la supprime dans ce cas. Il faut que la valeur du parametre soit bien définie
211     """
212     return original_narray(Eval(f),*tup,**args)
213 Numeric.array=array
214
215 #surcharge de la fonction sin de math pour les parametres
216 original_sin=math.sin
217 def sin(f): return Unop('sin', f)
218 Unop.opmap['sin']=lambda x: original_sin(x)
219 math.sin=sin
220
221 #surcharge de la fonction cos de math pour les parametres
222 original_cos=math.cos
223 Unop.opmap['cos']=lambda x: original_cos(x)
224 def cos(f): return Unop('cos', f)
225 math.cos=cos
226
227 #surcharge de la fonction sqrt de math pour les parametres
228 original_sqrt=math.sqrt
229 def sqrt(f): return Unop('sqrt', f)
230 Unop.opmap['sqrt']=lambda x: original_sqrt(x)
231 math.sqrt=sqrt
232
233 #surcharge de la fonction ceil de math pour les parametres
234 original_ceil=math.ceil
235 Unop.opmap['ceil']=lambda x: original_ceil(x)
236 def ceil(f): return Unop('ceil', f)
237 math.ceil=ceil