SmtC: Show me the Code
Ole Peter Smith
Instituto de Matemática e Estatística
Universidade Federal de Goiás
http://www.olesmith.com.br

Matemática Computacional
Problemas resolvemos na hora!
Milagres demoram mais um pouco...
Provérbio dinamarquês
< 9_Transformations | Code Listings | 1_Vector >
  1. Canvas2.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Canvas2.py.
    class Canvas2:
    
        P1=None
        P2=None
        R=None
    
        A=[0.0,0.0]
        B=[0.0,0.0]
    
        def __init__(self,r,p1,p2):
            self.R=r
            self.P1=p1
            self.P2=p2
            self.Initialize()
    
        def __str__(self):
           return str(self.P1)+" "+str(self.P2)+" "+str(self.R)+" "+str(self.A)+" "+ str(self.B)
    
        #Initialize Parameters A,B from R,P1 and P2
        
        def Initialize(self):
            self.A[0]=(1.0*(self.R[0] ))/(1.0*( self.P2[0]-self.P1[0] ))
            self.A[1]=(1.0*(self.R[1] ))/(1.0*( self.P1[1]-self.P2[1] ))
                                                       
            self.B[0]=-self.A[0]*self.P1[0]
            self.B[1]=-self.A[1]*self.P2[1]
            
    
        #Convert geometric point to pixels.
        
        def Point_2_Pixels(self,p):
            px=[0,0]
            for i in range(2):
                px[i]=self.A[i]*p[i]+self.B[i]
                
            return px
        
        #Convert geometric points to pixels.
        
        def Points_2_Pixels(self,ps):
            pxs=[]
            for p in ps:
                pxs.append(  self.Point_2_Pixels(p) )
                
            return pxs
    
  2. Carousel.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Carousel.py.
    from Tag import Tag
    from File import File_Read,File_Write
    
    class Carousel(Tag):
        Carousel_Header="Header.html"
        Carousel_Tailer="Tail.html"
    
        def Carousel_Generate(self,fname,title,files,resolution):
            html=[]
            html=html+File_Read(self.Carousel_Header)
            html=html+[ self.Tags("H1",title) ]
    
            tableoptions={
                "BORDER": '2px'
            }
            divoptions={
                "class": 'w3-content w3-section'
            }
            
            images=[]
            for file in files:
                img=self.Tag1(
                    "IMG",{
                        "class":  'mySlides',
                        "width":  resolution[0],
                        "height": resolution[1],
                        "src":    file,
                    }
                )
    
                images.append(img)
    
            div=self.Tags(
                "DIV",
                "\n".join(images),
                divoptions
            )
    
            div=self.Tags(
                "TABLE",
                self.Tags(
                    "TR",
                    self.Tags("TD",div)
                ),
                tableoptions
            )
            html=html+[ div ]
            html=html+File_Read(self.Carousel_Tailer)
            
            File_Write(fname,html,True)
    
  3. Circle.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Circle.py.
    from Vector import *
    from Curve  import Curve
    
    class Circle(Curve):
    
        Name="Circle"
        
        #Center
        C=Vector([0.0,0.0])
    
        #Radius
        r=0.0
    
        def __init__(self,r=1.0,C=None,NP=0):
            if (C): self.C=C
            if (NP): self.NP=NP
            
            self.r=r
            self.Closed=True
            
            return
        
        def R(self,t):
            return self.C+e(t)*self.r
    
        def PMin(self):
            return Vector([-self.r,-self.r])
        
        def PMax(self):
            return Vector([self.r,self.r])
    
  4. Circles.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Circles.py.
    from Vector import Vector,O
    from Circle import Circle
    
    curve=None
    
    C=O()
    files=[]
    for n in range(2,101):
        curve=Circle(1.0,C,n)
        curve.Rs()
    
        curve.Init_Canvas()
    
        fname="Circle/"+("%03d" % n)+".svg"
        options={
            "stroke": 'black',
            "style": {
                "stroke-width": 2,
            }
        }
        
        curve.Curve_SVG_Line_Write(fname,options)
        files.append(fname)
    
        
    curve.Curve_Carousel(files)
    
  5. Colors.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Colors.py.
    class Colors:
        def Colors_Convex(self,color1,color2,t):
            color=[]
            for i in range( len(color1) ):
                c=t*color2[i]+(1-t)*color1[i]
                color.append( str(c) )
    
            return color
    
  6. Curve.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Curve.py.
    from math import *
    from Vector import Vector
    
    from Canvas2 import Canvas2
    from SVG import SVG
    from File import File_Write
    from Carousel import Carousel
    
    class Curve(SVG,Carousel):
        Resolution=[300,300]
        Canvas=None
        Name="Curve"
    
        t1=0.0
        t2=2*pi
        NP=100
    
        Close=False
    
        def __init__(self):
            return
    
        def __str__(self):
            text=[]
            for n in range( len(self.rs) ):
                text.append(    str(self.ts[n])+": "+str(self.rs[n])   )
    
            return "\n".join(text)
    
    
        def Init_Canvas(self,pmin=None,pmax=None,resolution=None):
            if (not pmin): pmin=self.PMin()
            if (not pmax): pmax=self.PMax()
            if (not resolution): resolution=self.Resolution
            
            self.Canvas=Canvas2(resolution,pmin,pmax)
    
    
        def R(self,t):
            #Calculate point for parameter value t
            return Vector([
                cos(t),
                sin(t)
            ])
    
        def Rs(self):
            #Calculate self.NP points for parameter values between
            #self.t1 and self.t2
            dt=(self.t2-self.t1)/(1.0*(self.NP-1))
    
            #Store in self.rs and self.ts
            self.rs=[]
            self.ts=[]
            
            t=self.t1
            for i in range( self.NP ):
                self.rs.append( self.R(t) )
                self.ts.append(t)
                
                t+=dt
    
            self.Curve_MinMax()
            
            return self.rs
    
        PMin=Vector([0.0,0.0])
        PMax=Vector([0.0,0.0])
    
        def PMax(self):
            #Detect Maximum point
            #Feel free to override!
            
            if ( len(self.rs)==0 ): return O()
            
            pmax=self.rs[0]
            for i in range( 1,len(self.rs) ):
                pmax=pmax.Max(self.rs[i])
    
            return pmax
        
        def PMin(self):
            #Detect Maximum point
            #Feel free to override!
            
            if ( len(self.rs)==0 ): return O()
            
            pmin=self.rs[0]
            for i in range( 1,len(self.rs) ):
                pmin=pmin.Min(self.rs[i])
    
            return pmin
        
        def Curve_MinMax(self):
            self.PMin()
            self.PMax()
        
        def Pxs(self,rs=[]):
            if (not rs): rs=self.rs
            
            self.pxs=self.Canvas.Points_2_Pixels(rs)
    
            return self.pxs
        
        def Curve_SVG_Line(self,options,rs=[]):
            #Draw curve as line segments
            if (not rs): rs=self.rs
    
            pxs=self.Pxs(rs)
            
            svg=[]
            for i in range( 1,self.NP ):
                svg.append(   self.SVG_Line( pxs[i-1],pxs[i],options )   )
    
            if (self.Close):
                svg.append(   self.SVG_Line( pxs[len(pxs)-1],pxs[0],options )   )
                
            return svg
        
        def Curve_SVG_Line_Write(self,fname,options,rs=[]):
            self.SVG_2_File(
                fname,
                self.Curve_SVG_Line(options,rs)
            )
            
        def Curve_Carousel(self,files):
            return self.Carousel_Generate(
                self.Name+".html",
                self.Name,
                files,
                self.Resolution
            )
    
  7. Ellipse.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Ellipse.py.
    from math import *
    
    from Vector import *
    from Curve  import Curve
    
    class Ellipse(Curve):
        
        #Center
        C=Vector([0.0,0.0])
        
        #Half axis'
        a=0.0
        b=0.0
        
        def __init__(self,a=1.0,b=2.0,C=None,NP=0):
            if (C):  self.C=C
            if (NP): self.NP=NP
            
            self.a=a
            self.b=b
            
            self.Closed=True
            
            return
        
        def R(self,t):
            return Vector([
                self.C[0]+self.a*cos(t),
                self.C[1]+self.b*sin(t),
            ])
        
        def PMin(self):
            return Vector([-self.a,-self.a])
        
        def PMax(self):
            return Vector([self.a,self.a])
    
  8. Ellipsis.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Ellipsis.py.
    from Vector  import *
    from Ellipse import Ellipse
    
    C=O()
    a=2.0
    
    b1=1.0
    b2=2.0
    
    N=100
    
    db=1.0*(b2-b1)/( 1.0*(N-1) )
    
    b=b1
    for n in range(N):
        curve=Ellipse(a,b,C,N)
        curve.Rs()
    
        curve.Init_Canvas()
    
        fname="Ellipse/"+("%03d" % n)+".svg"
        options={
            "stroke": 'blue',
            "style": {
                "stroke-width": 2,
            }
        }
        
        curve.Curve_SVG_Line_Write(fname,options)
        b+=db
    
  9. Epicycloid.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Epicycloid.py.
    from math import *
    from Vector import *
    from Curve import Curve
    
    class Epicycloid(Curve):
        Name="Epicycloid"
        
        #Parameters
        R=1.0
        r=0.5
        
        NP=400
        
        t1=0
        t2=12.0*pi
    
        def __init__(self,R=1.0,r=0.0,NP=0):
            self.rR=R
            self.r=r
    
            self.Omega=(self.rR+self.r)/(self.r)
            
            if (NP): self.NP=NP
    
            return
    
        def R(self,t):
            return Vector([
                (self.rR+self.r)*cos(t)-self.r*cos(self.Omega*t),
                (self.rR+self.r)*sin(t)-self.r*sin(self.Omega*t),
            ])
    
        def PMin(self):
            maxx=self.rR+2.0*self.r
            return Vector([-maxx,-maxx])
    
        def PMax(self):
            maxx=self.rR+2.0*self.r
            return Vector([maxx,maxx])
    
  10. Epicycloids.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Epicycloids.py.
    from Vector import *
    from Epicycloid import Epicycloid
    
    
    R=1.0
    rss=[
        6.0,5.0,4.0,3.0,2.0,1.0,
        1.0/2.0,1.0/3.0,1.0/4.0,
        1.0/5.0,1.0/6.0
    ]
    
    N=100
    NP=400
    
    palette=[
        "red","yellow","oragne","blue",
        "green","black", "magenta",
        "cyan"
    ]
    
    color1=[255,0,0] #red
    color2=[0,0,255] #blue
    
    dt=1.0/(1.0*(len(rss)-1))
    
    files=[]
    ssvg=[]
    n=0
    t=0.0
    for r in rss:
        curve=Epicycloid(R,r,NP)
        curve.Rs()
        curve.Init_Canvas()
        fname=curve.Name+"/"+("%03d" % n)+".svg"
        options={
            "stroke": 'blue',
            "style": { "stroke-width": 2, }
        }
        svg=[]
        svg=svg+curve.Curve_SVG_Polyline(options)
        curve.SVG_2_File(fname,svg)
    
        options={
            "stroke": "rgb("+",".join(
                curve.Colors_Convex(color1,color2,t)
            )+")",
            "style": { "stroke-width": 2, }
        }
        ssvg=ssvg+curve.Curve_SVG_Polyline(options)
        files.append(fname)
        n+=1
        t+=dt
        
    curve.SVG_2_File(curve.Name+"/"+curve.Name+".svg",ssvg) 
    curve.Curve_Carousel(files)
    
  11. File.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/File.py.
    def File_Read(fname):
        f=open(fname,"r" )
        if (not f):
            print "Unable to read from file: ".fname
            exit()
            
        lines=f.read()
    
        f.close()
        return lines.split("\n")
    
    
    def File_Write(fname,lines,tell=False):
        #Remove trailing empty lines
        while (lines and not lines[ len(lines)-1 ]):
            lines.pop(len(lines)-1)
    
        f=open(fname,"w" )
        if (not f):
            print "Unable to write to file: ".fname
            exit()
            
        size=0
        for line in lines:
            f.write("%s\n" % line)
            size+=len(line)
                
        f.close()
    
        if (tell):
            if (tell!=True):
                fname=tell
            print "\t"+fname+" ("+str(size)+" bytes)"
        return True
    
  12. Hyperbola.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Hyperbola.py.
    from math import *
    
    from Vector import *
    from Curve  import Curve
    
    class Hyperbola(Curve):
        Name="Hyperbola"
        
        #Center
        C=Vector([0.0,0.0])
    
        #Parameters
        a=1.0
        b=0.0
    
        t1=-2.0
        t2=2.0
        
        def __init__(self,a=1.0,b=0.0,C=None,NP=0):
            if (C):  self.C=C
            if (NP): self.NP=NP
            
            self.a=a
            self.b=b
    
            return
        
        def R_Hyp(self,t):
            return Vector([
                self.C[0]+self.a*cosh(t),
                self.C[1]+self.a*sin(t),
            ])
        
        def R(self,s):
            return Vector([
                self.C[0]+self.a*sqrt(1.0+s**2.0),
                self.C[1]+self.b*s
            ])
    
        def Assymptotes(self):
            xm=self.a*sqrt(1.0+self.t2**2.0)
            ym=self.b*xm/(1.0*self.a)
    
            return [
                [
                    self.C+Vector([-xm,-ym]),
                    self.C+Vector([ xm, ym])
                ],
                [
                    self.C+Vector([ xm,-ym]),
                    self.C+Vector([-xm, ym])
                ]
            ]
            
        def Assymptotes_SVG(self,options):
            svg=[]
            for assymptote in self.Assymptotes():
                px1=curve.Canvas.Point_2_Pixels(assymptote[0])
                px2=curve.Canvas.Point_2_Pixels(assymptote[1])
                
                svg.append(  self.SVG_Line(px1,px2,options)   )
                
            return svg       
    
        def PMin(self):
            xymin=min(-self.a*sqrt(1.0+self.t2**2.0),-20.0*self.t2)
            return Vector([xymin,xymin])
        
        def PMax(self):
            xymax=min(self.a*sqrt(1.0+self.t2**2.0),20.0*self.t2)
            return Vector([xymax,xymax])
    
  13. Hyperbolas.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Hyperbolas.py.
    from Vector  import *
    from Hyperbola import Hyperbola
    
    C=O()
    a=2.0
    
    b1=1.0
    b2=20.0
    
    N=100
    
    db=1.0*(b2-b1)/( 1.0*(N-1) )
    
    A=[
        [-1.0,0.0 ],
        [ 0.0,1.0 ],
    ]
    
    R=[
        [-1.0,0.0 ],
        [ 0.0,1.0 ],
    ]
    RR=[
        [ 1.0,0.0 ],
        [ 0.0,-1.0] ,
    ]
    
    def PMin():
        xymin=-2.0*b2
        return Vector([xymin,xymin])
    def PMax():
        xymax=2.0*b2
        return Vector([xymax,xymax])
    
    
    
    b=b1
    
    svgfiles=[]
    curve=None
    
    for n in range(N):
        curve=Hyperbola(a,b,C,N)
        curve.Rs()
    
        curve.Init_Canvas(PMin(),PMax())
    
        fname="Hyperbola/"+("%03d" % n)+".svg"
        options={
            "stroke": 'blue',
            "style": {
                "stroke-width": 2,
            }
        }
        svg=[]
        
        #Hyperbolas embracing X
    
        #Left hand part
        rsm=Map_Linears(A,curve.rs,True)
        
        svg=svg+curve.Curve_SVG_Line(options,curve.rs)
        svg=svg+curve.Curve_SVG_Line(options,rsm)
        
        #Hyperbolas embracing Y
        rsp=curve.rs
            
        options[ "stroke" ]='green'
        
        #Upper part
        rsp=Map_Linears(R,curve.rs,True)
        
        svg=svg+curve.Curve_SVG_Line(
            options,
            rsp
        )
        
         #Lower part
        rrsp=Map_Linears(RR,rsp,True)
        
        #svg=svg+curve.Curve_SVG_Line(
        #    options,
        #    rrsp
        #)
        
        options[ "stroke" ]='red'
        assymptotes=curve.Assymptotes()
        for assymptote in assymptotes:
            px1=curve.Canvas.Point_2_Pixels(assymptote[0])
            px2=curve.Canvas.Point_2_Pixels(assymptote[1])
            svg=svg+[ curve.SVG_Line(px1,px2,options) ]
                
        
    
        curve.SVG_2_File(fname,svg)
        svgfiles.append(fname)
        
        b+=db
    curve.Curve_Carousel(svgfiles)
    
  14. Matrix.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Matrix.py.
    from Vector import Vector
    
    class Matrix(list):    
        def __init__(self,A,j=None):
            ## Matrix creator: allocates and/or initializes
            if (A):
                if (A.__class__.__name__=='int'):
                    #Just allocate
                    if (not j): j=A
                    for i in range(A):
                         
                elif (A.__class__.__name__ in [ 'Matrix' ] ):
                    #Copy content!
                    for i in range( len(A) ):
                        self.append(Vector([]))
                        for j in range( len(A[i]) ):
                            self[i].append( 1.0*A[i][j] )
                else:
                    print "Matrix.init: Invalid first argument type",A,"'"+A.__class__.__name__+"'"
                    exit()
                    
        def __str__(A):
            ## Matrix print: print as list of Vectors.
            text=[]
            for i in range( len(A) ):
                text.append( A[i].__str__() )
    
            return "{\n   "+",\n   ".join(text)+"\n}"
        
        def __add__(A,B):
            ## Matrix add: per row/column
            if ( len(A)!=len(B) ):
                print "Matrix.add: Incompatible dimensions",len(A),len(B)
                exit()
    
            #Matrix allocated with zeros (calloc)
            C=Matrix( len(A),len(A[0]) )
            for i in range( len(A) ):
                if ( len(A[i])!=len(B[i]) ):
                    print "Matrix.add, row",i,": Incompatible dimensions",len(A[i]),len(B[i])
                    exit()
                    
                for j in range( len(A[i]) ):
                    C[i][j]=1.0*( A[i][j]+B[i][j] )
    
            return C
                
        def __iadd__(A,B):
            return A+B
        
         
        def __mul__(A,B):
            ## Matrix mul: Branches over type of second argument, B:
    
            if (B.__class__.__name__ in [ 'int','float' ]):
                #Scalar: Return Matrix,
                return A.__mul_Scalar__(B)
                
            if (B.__class__.__name__ in [ 'Vector' ]):
                #Vector: Return Vector,
                return A.__mul_Vector__(B)
            
            if (B.__class__.__name__ in [ 'Matrix' ]):
                #Matrix: Return Matrix
                return A.__mul_Matrix__(B)
            
            print "Matrix.mul: Invalid second argument type",B
            exit()
            
        def __mul_Scalar__(A,c):
            #Cast int to float
            c*=1.0
            
            C=Matrix( len(A),len(A[0]) )
            for i in range( len(A) ):
                for j in range( len(A[i]) ):
                    C[i][j]=A[i][j]*c
    
            return C
    
        def __mul_Vector__(A,v):
            fv=Vector( len(A[0]) )
            for i in range( len(A) ):
                fv[i]=0.0
                for j in range( len(B) ):
                    fv[i]+=A[i][j]*B[j]
    
            return fv
        
        def __mul_Matrix__(A,B):
            C=Matrix( len(A[0]),len(B) )
    
            for i in range( len(A) ):
                for j in range( len(B[0]) ):
                    cij=0.0
                    for k in range( len(A[i]) ):
                        cij+=A[i][k]*B[k][j]
                        C[i].append( cij )
            return C
                
        def __rmul__(A,B):
            return A.__mul__(B)
        
        def __imul__(A,B):
            return A*B
        
        def __neg__(A):
            ##Matrix neg: opposed Matrix, -A
            return A*(-1.0)
        
        def __sub__(A,B):
            ## Matrix sub: per element
            return A-B
                
        def __isub__(A,B):
            return A-B
    
    def Matrix_Zero(m,n):
        return Matrix(m,n)
    
    def Matrix_Identity(n):
        I=Matrix(n)
        for i in range(n):
            I[i][i]=1.0
    
        return I
    
    def Matrix_Diagonal(v):
        D=Matrix( len(v) )
        for i in range(n):
            D[i][i]=v[i]
    
        return D
    
    def Matrix_Dyadic(v):
        D=Matrix( len(v) )
        for i in range(n):
            D[i][i]=v[i]*v[j]
    
        return D
    
    def Matrix_Vandermonte(v):
        V=Matrix(len(v))
        for i in range( len(v) ):
            fact=1.0
            for j in range( len(v) ):
                V[i][j]=fact
                fact*=v[i]
    
        return V
    
    def Matrix_Rotation(theta):
        return Matrix([
            [cos(theta),-sin(theta)],
            [sin(theta),cos(theta)],
        ]
    
  15. Parabola.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Parabola.py.
    from Vector import *
    from Curve  import Curve
    
    class Parabola(Curve):
    
        #Parameters
        a=1.0
        b=0.0
        c=0.0
    
        NP=100
        t1=-2.0
        t2=2.0
        
        def __init__(self,a=1.0,b=0.0,c=0.0,NP=0):
            self.a=a
            self.b=b
            self.c=c
            if (NP): self.NP=NP
            
            return
        
        def R(self,t):
            return Vector([
                t,
                self.a*t**2.0+self.b*t+self.c
            ])
    
        def PMin(self):
            return Vector([self.t1,-1.0])
        
        def PMax(self):
            return Vector([self.t2,self.t2**2.0 ])
        
        def Discriminant(self):
            return self.b**2.0-4.0*self.a*self.c
        
        def Vertex(self):
            return Vector([
                -self.b/(2.0*self.a),
                -self.Discriminant()/(4.0*self.a)
            ])
    
  16. Parabolas.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Parabolas.py.
    from Vector   import *
    from Parabola import Parabola
    
    a=1.0
    c=0.0
    
    b1=-2.0
    b2=2.0
    
    N=100
    NP=100
    
    db=1.0*(b2-b1)/( 1.0*(N-1) )
    
    parabola=Parabola(-a,0.0,c,NP)
    parabola.Rs()
    
    b=b1
    for n in range(N):
        curve=Parabola(a,b,c,NP)
        curve.Rs()
    
        curve.Init_Canvas()
    
        #Transfer Canvas
        parabola.Canvas=curve.Canvas
    
        fname="Parabola/"+("%03d" % n)+".svg"
        options={
            "stroke": 'blue',
            "style": {
                "stroke-width": 2,
            }
        }
    
        svg=[]
        svg=svg+curve.Curve_SVG_Line(options)
        
        options[ "stroke" ]='green'
        svg=svg+parabola.Curve_SVG_Line(options)
    
        vertex=curve.Vertex()
        vertexx=curve.Canvas.Point_2_Pixels(vertex)
        options[ "stroke" ]='red'
        svg=svg+[ curve.SVG_Point(vertexx,options) ]
    
        curve.SVG_2_File(fname,svg)
        
        b+=db
    
  17. Projection.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Projection.py.
    from Vector import *
    from Matrix  import *
    from Transformation  import *
    
    class Projection(Transformation):
        def __init__(self,theta=0.0):
            self.Dim=2
            self.A=Matrix_Diagonal([1.0,0.0])
            self.b=Vector(2)
    
            if (theta!=0.0):
                R=Matrix_Rotation(theta)
                RT=Matrix_Rotation(theta)
    
                self.A=R*self.A*RT
    
            return
    
  18. Reflection.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Reflection.py.
    from Vector import *
    from Matrix  import *
    from Transformation  import *
    
    class Reflection(Transformation):
        def __init__(self,theta=0.0):
            self.Dim=2
            self.A=Matrix_Diagonal([1.0,-1.0])
            self.b=Vector(2)
    
            if (theta!=0.0):
                R=Matrix_Rotation(theta)
                RT=Matrix_Rotation(theta)
    
                self.A=R*self.A*RT
    
            return
    
  19. Rotation.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Rotation.py.
    from Vector import *
    from Matrix  import *
    from Transformation  import *
    
    class Rotation(Transformation):
    
        def __init__(self,theta):
            self.Dim=2
            self.A=Matrix_Rotation(theta),
            self.b=Vector(self.Dim)
    
            return
    
  20. SVG.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/SVG.py.
    from Tag import Tag
    from File import File_Read,File_Write
    
    class SVG(Tag):
        Header="Header.svg"
    
        def SVG_2_File(self,fname,svg):
            text=File_Read(self.Header)
            text=text+[ self.SVG_Start() ]
            text=text+svg
            text=text+[ self.SVG_End() ]
            
            File_Write(fname,text,True)
    
        def SVG_Start(self,options={}):
            roptions=dict(options)
            
            roptions[ "version" ]=1.1
            
            roptions[ "width" ]=self.Resolution[0]
            roptions[ "height" ]=self.Resolution[1]
            roptions[ "viewbox" ]=" ".join([
                '0','0',
                str(self.Resolution[0]),
                str(self.Resolution[1])
            ])
            roptions[ "xmlns" ]='http://www.w3.org/2000/svg'
    
            return self.Tag("svg",roptions)
        
        def SVG_End(self):
            return self.Tag_Close("svg")
            
        def SVG_Point(self,px,options={},r=5):
            roptions=dict(options)
    
            roptions[ "cx" ]=px[0]
            roptions[ "cy" ]=px[1]
            roptions[ "r" ]=r
            
            return self.Tag1("circle",roptions)
        
        def SVG_Line(self,px1,px2,options={}):
            roptions=dict(options)
    
            roptions[ "x1" ]=px1[0]
            roptions[ "y1" ]=px1[1]
            roptions[ "x2" ]=px2[0]
            roptions[ "y2" ]=px2[1]
            
            return self.Tag1("line",roptions)
    
  21. Scaling.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Scaling.py.
    from Vector import *
    from Matrix  import *
    from Transformation  import *
    
    class Scaling(Transformation):
        def __init__(self,lambda1,lambda2=1.0,theta=0.0):
            self.Dim=2
            self.A=Matrix_Diagonal([lambda1,lambda2])
            self.b=Vector(2)
    
            if (theta!=0.0):
                R=Matrix_Rotation(theta)
                RT=Matrix_Rotation(theta)
    
                self.A=R*self.A*RT
    
            return
    
  22. Tag.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Tag.py.
    class Tag():
        def Options_2_Text(self,options):
            #Get a copy!
            roptions=dict(options)
    
            if options.has_key("style"):
                styles=[]
                soptions=sorted(options[ "style" ])
                for opt in soptions:
                    text=opt+": "+str(   roptions[ "style" ][ opt ]   )
                    styles.append(text)
    
                roptions[ "style" ]="; ".join(styles)
    
            rroptions=[]
            soptions=sorted(roptions.keys())
            for key in soptions:
                text=key+'="'+str(   roptions[ key ]   )+'"'
                rroptions.append(text)
    
            empty=""
            if (len(rroptions)>0): empty=" "
    
            return empty+" ".join(rroptions)
        
        def Tag(self,tag,options):
            return "<"+tag+self.Options_2_Text(options)+">"
        
        def Tag1(self,tag,options):
            return "<"+tag+self.Options_2_Text(options)+"/>"
        
        def Tags(self,tag,contents,options={}):
            return "<"+tag+self.Options_2_Text(options)+">"+contents+self.Tag_Close(tag)
        
        def Tag_Close(self,tag):
            return "</"+tag+">"
    
  23. Transformation.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Transformation.py.
    from Vector import *
    from Matrix  import *
    
    class Transformation():
        Dim=2
        
        #Matrix A and vector b: f(v)=A*v+n
        A=None
        b=None
    
        def __init__(self,A=[],b=[],dim=2):
            self.Dim=dim
            if (A): self.Dim=len(A)
    
            if (not A): self.A=Matrix_Identity(self.Dim)
            if (not b): self.A=b=Vector_O(self.Dim)
    
            return
    
  24. Translation.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Translation.py.
    from Vector import *
    from Matrix  import *
    from Transformation  import *
    
    class Translation(Transformation):
    
        def __init__(self,b):
            self.Dim=len(b)
            self.A=Matrix(self.Dim)
            self.b=b
    
            return
    
  25. Trochoid.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Trochoid.py.
    from math import *
    
    from Vector import *
    from Curve  import Curve
    
    class Trochoid(Curve):
        Name="Trochoid"
    
        #Parameters
        a=1.0
        b=0.0
    
        NP=400
        t1=0
        t2=8.0*pi
        
        def __init__(self,a=1.0,b=0.0,NP=0):
            self.a=a
            self.b=b
            if (NP): self.NP=NP
            
            return
        
        def R(self,t):
            return Vector([
                self.a*t-(self.a+self.b)*sin(t),
                self.a-(self.a+self.b)*cos(t)
            ])
    
        def PMin(self):
            return Vector([self.t1,-1.5])
        
        def PMax(self):
            return Vector([self.t2,4.0 ])
    
  26. Trochoids.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Trochoids.py.
    from Vector   import *
    from Trochoid import Trochoid
    
    a=1.0
    
    b1=-2.0
    b2=2.0
    
    N=100
    NP=400
    
    db=1.0*(b2-b1)/( 1.0*(N-1) )
    
    cycloid=Trochoid(a,0.0,NP)
    cycloid.Rs()
    
    palette=[
        "red","yellow","oragne","blue","green","black",
        "magenta","cyan"
    ]
    
    b=b1
    
    files=[]
    
    ssvg=[]
    for n in range(N):
        curve=Trochoid(a,b,NP)
        curve.Rs()
    
        curve.Init_Canvas()
    
        #Transfer Canvas
        cycloid.Canvas=curve.Canvas
    
        fname="Trochoid/"+("%03d" % n)+".svg"
        options={
            "stroke": 'blue',
            "style": {
                "stroke-width": 2,
            }
        }
    
        svg=[]
        svg=svg+curve.Curve_SVG_Line(options)
        
        options={
            "stroke": palette[ (n % len(palette)) ],
            "style": {
                "stroke-width": 2,
            }
        }
    
        ssvg=ssvg+curve.Curve_SVG_Line(options)
        
        options[ "stroke" ]='green'
        svg=svg+cycloid.Curve_SVG_Line(options)
    
        curve.SVG_2_File(fname,svg)
        files.append(fname)
    
        b+=db
    curve.Curve_Carousel(files)
    
    curve.SVG_2_File("Trochoid/Trochoids.svg",ssvg)
    
  27. Vector.py:
    Python Listing: /usr/local/Slides/1_Disciplines/2_MC/Code/Vector.py.
    from math import *
    
    class Vector(list):
        def __init__(v,w=[]):
            if (w.__class__.__name__=="int"):
                v.__Calloc__(w)
                
            else:
                v.__Calloc__( len(w) )
                for i in range( len(w) ):
                    v[i]=1.0*w[i]
            
        def __Calloc__(v,size):
            for i in range(size):
                v.append(0.0)
            
        def __add__(v,w):        
            #Binary add: u=v+w
            u=Vector(v)
            for i in range(len(v)):
                u[i]+=w[i]
            return u
    
        def __iadd__(v,w):
            #Unary add: u+=v. Superflous?
            return v+w
    
        
        def __sub__(v,w):
            #Binary subtraction: u=v-w
            u=Vector(v)
            for i in range(len(v)):
                u[i]-=w[i]
            
            return u
    
        def __isub__(v,w):
            #Unary subtraction: u-=v.
            return v-w
    
        def __neg__(u):
            #Vector neg: opposed vector
            return u*(-1.0)
        
        
        def __mul__(v,arg2):
            
            if (arg2.__class__.__name__=="Vector"):
                return v.__mul_Vector__(arg2)
    
            #Second argument should be e scalar from now on.
            
            #Make sure it is float
            if (arg2.__class__.__name__=="int"):
                arg2*=1.0
                
            if (arg2.__class__.__name__=="float"):
                return v.__mul_Scalar__(arg2)
    
            print "Vector.__mul__: Invalid second argument: ",arg2.__class__.__name__
    
        def __mul_Scalar__(v,c):
            #Vector with Scalar: Vector
            u=Vector(v)
            for i in range( len(v) ):
                u[i]*=c
            return u
        
        def __mul_Vector__(v,w):
            #Vector with Vector: Scalar
            dot=0.0
            for i in range( len(v) ):
                dot+=v[i]*w[i]
                
            return dot
            
        def __imul__(v,w):
            #Unary multiplication: u=*v
            return v*w
    
        def __str__(v):
            #Diferentiate print vectors.
            text=[]
            for vi in v:
                text.append( str(vi) )
    
            return "{"+",".join(text)+"}"
    
        def DotProduct(v,w):
            return v*w
        
        def SqLength(v):
            return v*v
        
        def Length(v):
            return sqrt( v.SqLength() )
        
        def Normalize(v,length=1.0):
            w=Vector()
            if (v.Length()>0.0):
                w=v*(1.0/v.Length())
        
        def Hat2(v):
            return Vector([ -v[1],v[0] ])
    
        def Projection(v,e):
            return e*(v*e)/e.SqLength()
        
        def Complement(v,e):
            return v-v.Projection(e)
    
        def Map_Linear(v,A):
            #Returns A*v
            u=Vector()
            for i in range( len(v) ):
                u.append(0.0)
                for j in range( len(v) ):
                    u[i]+=A[i][j]*v[j]
    
            return u
        
        def Map_Affin(v,A,b=None):
            #Returns A*v+b
            u=Vector()
            for i in range( len(v) ):
                u.append(0.0)
                for j in range( len(v) ):
                    u[i]+=A[i][j]*v[j]
                    if (b):
                        u[i]+=b[j]
    
            return u
    
        def Min(v,w):
            u=Vector( len(v) )
            for i in range( len(v) ):
                u[i]=min(v[i],w[i])
    
            return u
        
        def Max(v,w):
            u=Vector( len(v) )
            for i in range( len(v) ):
                u[i]=max(v[i],w[i])
    
            return u
    
    def O(dim=2):
        #Origin
        return Vector(dim)
    
    #Unit Vectors
    
    def i():
        return Vector([1.0,0.0])
    
    def j():
        #i's complement (normal)
        return Vector([0.0,1.0])
    
    def e(t):
        return Vector([
            cos(t),
            sin(t)
        ])
    
    def f(t):
        #e's complement (normal)
        return Vector([
            -sin(t),
            cos(t)
        ])
    
    def p(t):
        return Vector([
            cos(t),
            -sin(t)
        ])
    
    def q(t):
        #q's complement (normal)
        return Vector([
            sin(t),
            cos(t)
        ])
    
    
    def Map_Affins(A,B,ps,tell=0):
        rps=[]
        for p in ps:
            rp=p.Map_Affin(A,B)
            
            rps.append(rp)
            if (tell): print p,"-->",rp
    
        return rps
    
    def Map_Linears(A,ps,tell=0):
        #Maps ps: f(p)=A*p
        rps=[]
        for p in ps:
            rp=p.Map_Linear(A)
            
            rps.append(rp)
            if (tell): print p,"-->",rp
    
        return rps
    
< 9_Transformations | Code Listings | 1_Vector >
Messages:
0 secs.