/[escript]/trunk/pycad/py_src/primitives.py
ViewVC logotype

Diff of /trunk/pycad/py_src/primitives.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 915 by gross, Thu Dec 14 06:12:53 2006 UTC revision 916 by gross, Fri Dec 15 08:25:57 2006 UTC
# Line 33  def resetGlobalPrimitiveIdCounter(): Line 33  def resetGlobalPrimitiveIdCounter():
33     global global_primitive_id_counter     global global_primitive_id_counter
34     global_primitive_id_counter=1     global_primitive_id_counter=1
35    
36    def setToleranceForColocation(tol=1.e-11):
37       global global_tolerance_for_colocation
38       global_tolerance_for_colocation=tol
39    
40    def getToleranceForColocation():
41       return global_tolerance_for_colocation
42    
43  resetGlobalPrimitiveIdCounter()  resetGlobalPrimitiveIdCounter()
44    setToleranceForColocation()
45    
46  class Primitive(object):  class Primitive(object):
47      """      """
# Line 54  class Primitive(object): Line 62  class Primitive(object):
62         return "%s(%s)"%(self.__class__.__name__,self.getID())         return "%s(%s)"%(self.__class__.__name__,self.getID())
63      def __cmp__(self,other):      def __cmp__(self,other):
64         return cmp(self.getID(),other.getID())         return cmp(self.getID(),other.getID())
65      def getPoints(self):  
66        def getConstructionPoints(self):
67          """          """
68          returns the C{set} of points used to construct the primitive          returns the points used to construct the primitive
69          """          """
70          out=set()          out=set()
71          for i in self.getHistory():          for i in self.getPrimitives():
72             if isinstance(i,Point): out.add(i)             if isinstance(i,Point): out.add(i)
73          return out          return list(out)
74    
75      def setLocalScale(self,factor=1.):      def getPrimitives(self):
76          """          """
77          sets the local refinement factor          returns primitives used to construct the primitive
78          """          """
79          for p in self.getPoints(): p.setLocalScale(factor)          return []
80    
     def isPoint(self):  
         """  
         returns C{True} is the primitive is a L{Point}  
         """  
         return False  
     def isCurve(self):  
         """  
         returns C{True} is the primitive is a L{Curve}  
         """  
         return False  
     def isSurface(self):  
         """  
         returns C{True} is the primitive is a L{Surface}  
         """  
         return False  
     def isCurveLoop(self):  
         """  
         returns C{True} is the primitive is a L{CurveLoop}  
         """  
         return False  
     def isSurfaceLoop(self):  
         """  
         returns C{True} is the primitive is a L{SurfaceLoop}  
         """  
         return False  
     def getHistory(self):  
         """  
         returns C{set} of primitive used to construct the primitive  
         """  
         return set()  
81      def copy(self):      def copy(self):
82         """         """
83         returns a copy of the object         returns a deep copy of the object
84         """         """
85         return Primitive()         return Primitive()
86    
     def apply(self,transformation):  
         """  
         returns a new object by applying the transformation  
         """  
         raise NotImplementedError("apply is not implemented for this class %s."%self.__class__.__name__)  
87    
88      def modifyBy(self,transformation):      def modifyBy(self,transformation):
89          """         """
90          modifies the object by applying a transformation         modifies the coordinates by applying a transformation
91          """         """
92          raise NotImplementedError("modifyBy not implemented for this class %s."%self.__class__.__name__)         for p in self.getConstructionPoints(): p.modifyBy(transformation)
93    
94    
95      def __add__(self,other):      def __add__(self,other):
96          """          """
# Line 169  class Primitive(object): Line 144  class Primitive(object):
144          elif isinstance(other,Transformation):          elif isinstance(other,Transformation):
145              trafo=other              trafo=other
146          else:          else:
147              raise TypeError, "cannot convert argument to Trnsformation class object."              raise TypeError, "cannot convert argument to Transformation class object."
148          return self.apply(trafo)          return self.apply(trafo)
149    
150      def __neg__(self):      def __neg__(self):
151          return ReversedPrimitive(self)          return ReversedPrimitive(self)
152    
153      def getGmshCommand(self):      def setLocalScale(self,factor=1.):
154           """
155           sets the local refinement factor
156           """
157           for p in self.getConstructionPoints(): p.setLocalScale(factor)
158    
159        def getGmshCommand(self, local_scaling_factor=1.):
160            """
161            returns the Gmsh command(s) to create the primitive
162            """
163          raise NotImplementedError("getGmshCommand is not implemented for this class %s."%self.__class__.__name__)          raise NotImplementedError("getGmshCommand is not implemented for this class %s."%self.__class__.__name__)
164    
165        def apply(self,transformation):
166            """
167            returns a new object by applying the transformation
168            """
169            raise NotImplementedError("apply is not implemented for this class %s."%self.__class__.__name__)
170    
171        def isColocated(self,primitive):
172           """
173           returns True is the two primitives are located at the smae position
174           """
175           raise NotImplementedError("isColocated is not implemented for this class %s."%self.__class__.__name__)
176    
177  class Point(Primitive):  class Point(Primitive):
178      """      """
179      a three dimensional point      a three dimensional point
# Line 216  class Point(Primitive): Line 212  class Point(Primitive):
212         else:         else:
213            self._x=x            self._x=x
214    
215      def getHistory(self):      def getPrimitives(self):
216         """         """
217         returns C{set} of primitive used to construct the primitive         returns primitives used to construct the primitive
218         """         """
219         return set([self])         return [self]
220    
221      def isColocated(self,point,tol=1.e-11):      def isColocated(self,primitive):
222         """         """
223         returns True if L{Point} point is colocation (same coordinates)         returns True if L{Point} primitive is colocation (same coordinates)
224         that means if |self-point| <= tol * max(|self|,|point|)         that means if |self-primitive| <= tol * max(|self|,|primitive|)
225         """         """
226         if isinstance(point,Point):         if isinstance(primitive,Point):
227            point=point.getCoordinates()            primitive=primitive.getCoordinates()
228         c=self.getCoordinates()            c=self.getCoordinates()
229         d=c-point            d=c-primitive
230         return numarray.dot(d,d)<=tol**2*max(numarray.dot(c,c),numarray.dot(point,point))            return numarray.dot(d,d)<=getToleranceForColocation()**2*max(numarray.dot(c,c),numarray.dot(primitive,primitive))
231           else:
232              return False
233    
234      def copy(self):      def copy(self):
235         """         """
236         returns a copy of the point         returns a deep copy of the point
237         """         """
238         c=self.getCoordinates()         c=self.getCoordinates()
239         return Point(c[0],c[1],c[2],local_scale=self.getLocalScale())         return Point(c[0],c[1],c[2],local_scale=self.getLocalScale())
# Line 254  class Point(Primitive): Line 252  class Point(Primitive):
252          new_p.modifyBy(transformation)          new_p.modifyBy(transformation)
253          return new_p          return new_p
254    
   
255      def getGmshCommand(self, local_scaling_factor=1.):      def getGmshCommand(self, local_scaling_factor=1.):
256            """
257            returns the Gmsh command(s) to create the primitive
258            """
259          c=self.getCoordinates()          c=self.getCoordinates()
260          return "Point(%s) = {%s , %s, %s , %s };"%(self.getID(),c[0],c[1],c[2], self.getLocalScale()*local_scaling_factor)          return "Point(%s) = {%s , %s, %s , %s };"%(self.getID(),c[0],c[1],c[2], self.getLocalScale()*local_scaling_factor)
261    
262  class Curve(Primitive):  class Primitive1D(Primitive):
263        """        """
264        a curve        general one-dimensional primitive
265        """        """
266        def __init__(self,*args):        def __init__(self,*args):
267            """            """
268            defines a curve form a set of control points            create a one-dimensional primitive
269              """
270              super(Primitive1D, self).__init__()
271          
272    class Curve(Primitive1D):
273        """
274        a curve defined through a list of control points.
275        """
276        def __init__(self,*points):
277            """            """
278              defines a curve form control points
279              """
280              if len(points)<2:
281                 raise TypeError("Curve needs at least two points")
282            super(Curve, self).__init__()            super(Curve, self).__init__()
283            l=len(args)            i=0
284            for i in range(l):            for p in points:
285                if not args[i].isPoint():                i+=1
286                   raise TypeError("%s-th argument is not a Point object."%i)                if not isinstance(p,Point): raise TypeError("%s-th argument is not a Point object."%i)
287            self.__nodes=args            self.__points=points
288        def __len__(self):  
289            return len(self.__nodes)      def __len__(self):
290        def isCurve(self):            """
291          return True            returns the number of control points
292        def getStart(self):            """
293              return len(self.__points)
294    
295        def getStartPoint(self):
296           """           """
297           returns start point           returns start point
298           """           """
299           return self.__nodes[0]           return self.__points[0]
300    
301        def getEnd(self):      def getEndPoint(self):
302           """           """
303           returns end point           returns end point
304           """           """
305           return self.__nodes[-1]           return self.__points[-1]
306    
307        def getNodes(self):      def getControlPoints(self):
308           """           """
309           returns a list of the nodes           returns a list of the points
310           """           """
311           return self.__nodes           return self.__points
312        def getGmshCommand(self):  
313        def getPrimitives(self):
314           """
315           returns primitives used to construct the Curve
316           """
317           out=set()
318           for p in self.getControlPoints(): out|=set(p.getPrimitives())
319           out.add(self)
320           return list(out)
321    
322        def copy(self):
323           """
324           returns a deep copy
325           """
326           new_p=[]
327           for p in self.getControlPoints(): new_p.append(p.copy())
328           return self.__class__(*tuple(new_p))
329    
330    
331        def apply(self,transformation):
332            """
333            applies transformation
334            """
335            new_p=[]
336            for p in self.getControlPoints(): new_p.append(p.apply(transformation))
337            return self.__class__(*tuple(new_p))
338    
339        def isColocated(self,primitive):
340           """
341           returns True curves are on the same position
342           """
343           if isinstance(primitive,self.__class__):
344              if len(primitive) == len(self):
345                 cp0=self.getControlPoints()
346                 cp1=primitive.getControlPoints()
347                 for i in range(len(cp0)):
348                    if not cp0[i].isColocated(cp1[i]):
349                       return False
350                 return True
351              else:
352                 return False
353           else:
354              return False
355    
356    class Spline(Curve):
357        """
358        a spline curve defined through a list of control points.
359        """
360        def getGmshCommand(self):
361            """
362            returns the Gmsh command(s) to create the Curve
363            """
364          out=""          out=""
365          for i in self.getNodes():          for i in self.getControlPoints():
366              if len(out)>0:              if len(out)>0:
367                  out+=", %s"%i.getID()                  out+=", %s"%i.getID()
368              else:              else:
369                  out="%s"%i.getID()                  out="%s"%i.getID()
370          return "Spline(%s) = {%s};"%(self.getID(),out)          return "Spline(%s) = {%s};"%(self.getID(),out)
371        def getHistory(self):      
           out=set([self])  
           for i in self.getNodes(): out|=i.getHistory()  
           return out  
       def getPoints(self):  
         out=set()  
         for i in self.getNodes(): out|=i.getPoints()  
         return out  
   
372    
373  class BezierCurve(Curve):  class BezierCurve(Curve):
374      """      """
375      a Bezier curve      a Bezier curve
376      """      """
     def __neg__(self):  
          """  
          returns the line segment with swapped start and end points  
          """  
          return BezierCurve(self.getNodes()[::-1])  
     def __add__(self,other):  
          return BezierCurve([p+other for p in self.getNodes()])  
377      def getGmshCommand(self):      def getGmshCommand(self):
378            """
379            returns the Gmsh command(s) to create the Curve
380            """
381          out=""          out=""
382          for i in self.getNodes():          for i in self.getControlPoints():
383              if len(out)>0:              if len(out)>0:
384                  out+=", %s"%i.getID()                  out+=", %s"%i.getID()
385              else:              else:
386                  out="%s"%i.getID()                  out="%s"%i.getID()
387          return "Bezier(%s) = {%s};"%(self.getID(),out)          return "Bezier(%s) = {%s};"%(self.getID(),out)
388    
389  class BSplineCurve(Curve):  class BSpline(Curve):
390      """      """
391      a BSpline curve. Control points may be repeated.      a BSpline curve. Control points may be repeated.
392      """      """
     def __neg__(self):  
          """  
          returns the line segment with swapped start and end points  
          """  
          return BSplineCurve(self.getNodes()[::-1])  
     def __add__(self,other):  
          return BSplineCurve([p+other for p in self.getNodes()])  
393      def getGmshCommand(self):      def getGmshCommand(self):
394            """
395            returns the Gmsh command(s) to create the Curve
396            """
397          out=""          out=""
398          for i in self.getNodes():          for i in self.getControlPoints():
399              if len(out)>0:              if len(out)>0:
400                  out+=", %s"%i.getID()                  out+=", %s"%i.getID()
401              else:              else:
# Line 356  class Line(Curve): Line 406  class Line(Curve):
406      """      """
407      a line is defined by two L{Point}s      a line is defined by two L{Point}s
408      """      """
409      def __init__(self,start,end):      def __init__(self,*points):
410          """          """
411          defines a curve form a set of control points          defines a line with start and end point
412          """          """
413          super(Line, self).__init__(start,end)          if len(points)!=2:
414      def __neg__(self):             raise TypeError("Line needs two points")
415         return ReversedPrimitive(self)          super(Line, self).__init__(*points)
     def __add__(self,other):  
        return Line(self.getEnd()+other,self.getStart()+other)  
416      def getGmshCommand(self):      def getGmshCommand(self):
417          return "Line(%s) = {%s, %s};"%(self.getID(),self.getStart().getID(),self.getEnd().getID())          """
418            returns the Gmsh command(s) to create the Curve
419            """
420            return "Line(%s) = {%s, %s};"%(self.getID(),self.getStartPoint().getID(),self.getEndPoint().getID())
421    
422    
423  class Arc(Curve):  class Arc(Primitive1D):
424      """      """
425      defines an arc      defines an arc
426      """      """
# Line 376  class Arc(Curve): Line 428  class Arc(Curve):
428         """         """
429         creates an arc by the start point, end point and center         creates an arc by the start point, end point and center
430         """         """
431         if center.isPoint():         if isinstance(center,Point): raise TypeError("center needs to be a Point object.")
432             raise TypeError("center needs to be a Point object.")         if isinstance(end,Point): raise TypeError("end needs to be a Point object.")
433         super(Arc, self).__init__(start,end)         if isinstance(start,Point): raise TypeError("start needs to be a Point object.")
434           super(Arc, self).__init__()
435         self.__center=center         self.__center=center
436           self.__start=start
437           self.__end=end
438    
439      def getCenter(self):      def getStartPoint(self):
440           """
441           returns start point
442           """
443           return self.__start
444    
445        def getEndPoint(self):
446           """
447           returns end point
448           """
449           return self.__end
450    
451        def getCenterPoint(self):
452         """         """
453         returns center         returns center
454         """         """
455         return self.__center         return self.__center
     def __add__(self,other):  
        return Arc(self.getCenter()+other,self.getStart()+other,self.getEnd()+other)  
456    
457      def getHistory(self):      def getPrimitives(self):
458            out=set([self])         """
459            out|=self.getCenter().getHistory()         returns C{set} of primitive used to construct the Curve
460            for i in self.getNodes(): out|=i.getHistory()         """
461            return out         out=set()
462      def getPoints(self):         out|=set(self.getStartPoint().getPrimitives())
463            out=self.getCenter().getPoints()         out|=set(self.getEndPoint().getPrimitives())
464            for i in self.getNodes(): out|=i.getPoints()         out|=set(self.getCenterPoint().getPrimitives())
465            return out         out.add(self)
466           return list(out)
467    
468      def getGmshCommand(self):      def getGmshCommand(self):
469          return "Circle(%s) = {%s, %s, %s};"%(self.getID(),self.getStart().getID(),self.getCenter().getID(),self.getEnd().getID())         """
470           returns the Gmsh command(s) to create the primitive
471           """
472           return "Circle(%s) = {%s, %s, %s};"%(self.getID(),self.getStartPoint().getID(),self.getCenterPoint().getID(),self.getEndPoint().getID())
473    
474        def copy(self):
475           """
476           returns a deep copy
477           """
478           return Arc(self.getCenterPoint().copy(),self.getStartPoint().copy(),self.getEndPoint().copy())
479    
480        def apply(self,transformation):
481            """
482            applies transformation
483            """
484            return Arc(self.getCenterPoint().apply(transformation),self.getStartPoint().apply(transformation),self.getEndPoint().apply(transformation))
485    
486        def isColocated(self,primitive):
487           """
488           returns True curves are on the same position
489           """
490           if isinstance(primitive,Arc):
491                if not self.getCenterPoint().isColocated(primitive.getCenterPoint()): return False
492                if not self.getEndPoint().isColocated(primitive.getEndPoint()): return False
493                if not self.getStartPoint().isColocated(primitive.getStartPoint()): return False
494                return True
495           else:
496              return False
497    
498    
499    #=================================================================================================================================
500  class CurveLoop(Primitive):  class CurveLoop(Primitive):
501      """      """
502      An oriented loop of curves.      An oriented loop of curves.
# Line 428  class CurveLoop(Primitive): Line 524  class CurveLoop(Primitive):
524         return CurveLoop(*tuple([c+other for c in self.getCurves()[::-1]]))         return CurveLoop(*tuple([c+other for c in self.getCurves()[::-1]]))
525      def __len__(self):      def __len__(self):
526         return len(self.__curves)         return len(self.__curves)
527      def getHistory(self):      def getPrimitives(self):
528            out=set([self])            out=set([self])
529            for i in self.getCurves(): out|=i.getHistory()            for i in self.getCurves(): out|=i.getPrimitives()
530            return out            return out
531      def getPoints(self):      def getConstructionPoints(self):
532            out=set()            out=set()
533            for i in self.getCurves(): out|=i.getPoints()            for i in self.getCurves(): out|=i.getConstructionPoints()
534            return out            return out
535      def getGmshCommand(self):      def getGmshCommand(self):
536          out=""          out=""
# Line 465  class Surface(Primitive): Line 561  class Surface(Primitive):
561         return self.__loop         return self.__loop
562      def __add__(self,other):      def __add__(self,other):
563         return Surface(self.getBoundaryLoop()+other)         return Surface(self.getBoundaryLoop()+other)
564      def getHistory(self):      def getPrimitives(self):
565          out=set([self]) | self.getBoundaryLoop().getHistory()          out=set([self]) | self.getBoundaryLoop().getPrimitives()
566          return out          return out
567      def getPoints(self):      def getConstructionPoints(self):
568          return self.getBoundaryLoop().getPoints()          return self.getBoundaryLoop().getConstructionPoints()
569      def getGmshCommand(self):      def getGmshCommand(self):
570          return "Ruled Surface(%s) = {%s};"%(self.getID(),self.getBoundaryLoop().getID())          return "Ruled Surface(%s) = {%s};"%(self.getID(),self.getBoundaryLoop().getID())
571    
# Line 495  class PlaneSurface(Surface): Line 591  class PlaneSurface(Surface):
591         return self.__holes         return self.__holes
592      def __add__(self,other):      def __add__(self,other):
593         return PlaneSurface(self.getBoundaryLoop()+other, holes=[h+other for h in self.getHoles()])         return PlaneSurface(self.getBoundaryLoop()+other, holes=[h+other for h in self.getHoles()])
594      def getHistory(self):      def getPrimitives(self):
595          out=set([self]) | self.getBoundaryLoop().getHistory()          out=set([self]) | self.getBoundaryLoop().getPrimitives()
596          for i in self.getHoles(): out|=i.getHistory()          for i in self.getHoles(): out|=i.getPrimitives()
597          return out          return out
598      def getPoints(self):      def getConstructionPoints(self):
599          out=self.getBoundaryLoop().getPoints()          out=self.getBoundaryLoop().getConstructionPoints()
600          for i in self.getHoles(): out|=i.getPoints()          for i in self.getHoles(): out|=i.getConstructionPoints()
601          return out          return out
602      def getGmshCommand(self):      def getGmshCommand(self):
603          out=""          out=""
# Line 562  class SurfaceLoop(Primitive): Line 658  class SurfaceLoop(Primitive):
658         return SurfaceLoop([c+other for c in self.getSurfaces])         return SurfaceLoop([c+other for c in self.getSurfaces])
659      def __len__(self):      def __len__(self):
660         return len(self.__surfaces)         return len(self.__surfaces)
661      def getHistory(self):      def getPrimitives(self):
662            out=set([self])            out=set([self])
663            for i in self.getSurfaces(): out|=i.getHistory()            for i in self.getSurfaces(): out|=i.getPrimitives()
664            return out            return out
665      def getPoints(self):      def getConstructionPoints(self):
666            out=set()            out=set()
667            for i in self.getSurfaces(): out|=i.getPoints()            for i in self.getSurfaces(): out|=i.getConstructionPoints()
668            return out            return out
669      def getGmshCommand(self):      def getGmshCommand(self):
670          out=""          out=""
# Line 606  class Volume(Primitive): Line 702  class Volume(Primitive):
702         return self.__loop         return self.__loop
703      def __add__(self,other):      def __add__(self,other):
704         return Volume(self.getSurfaceLoop()+other, holes=[h+other for h in self.getHoles()])         return Volume(self.getSurfaceLoop()+other, holes=[h+other for h in self.getHoles()])
705      def getHistory(self):      def getPrimitives(self):
706          out=set([self]) | self.getSurfaceLoop().getHistory()          out=set([self]) | self.getSurfaceLoop().getPrimitives()
707          for i in self.getHoles(): out|=i.getHistory()          for i in self.getHoles(): out|=i.getPrimitives()
708          return out          return out
709      def getPoints(self):      def getConstructionPoints(self):
710          out=self.getSurfaceLoop().getPoints()          out=self.getSurfaceLoop().getConstructionPoints()
711          for i in self.getHoles(): out|=i.Points()          for i in self.getHoles(): out|=i.Points()
712          return out          return out
713      def getGmshCommand(self):      def getGmshCommand(self):
# Line 645  class PropertySet(Primitive): Line 741  class PropertySet(Primitive):
741         super(PropertySet, self).__init__()         super(PropertySet, self).__init__()
742         self.__items=items         self.__items=items
743         self.__tag=tag         self.__tag=tag
744      def getHistory(self):      def getPrimitives(self):
745          out=set([self, self.getBoundaryLoop().getHistory()])          out=set([self, self.getBoundaryLoop().getPrimitives()])
746          for i in self.getHoles(): out|=i.getHistory()          for i in self.getHoles(): out|=i.getPrimitives()
747          return out          return out
748    
749  class PrimitiveStack(object):  class PrimitiveStack(object):
750        def __init__(self,*items):        def __init__(self,*items):
751          self.__prims=set()          self.__prims=set()
752          for i in items:          for i in items:
753              self.__prims|=i.getHistory()              self.__prims|=i.getPrimitives()
754          self.__prims=list(self.__prims)          self.__prims=list(self.__prims)
755          self.__prims.sort()          self.__prims.sort()
756    

Legend:
Removed from v.915  
changed lines
  Added in v.916

  ViewVC Help
Powered by ViewVC 1.1.26