Monday, 13 January 2014

Typical degree problem & Python: Part 3

Problem 3 formulation:

Given a line described by ax+by+c=0, create a function script with the values a,b,c as input that prints:

1-The affine transformation matrix obtained by creating a symmetry respect to the line

2-A plot of a circle with 1 unit radius centered on (0,0) and its reflection



Solution:

##### Libraries #####

from numpy import *

import math as mt # Mistake corrected

import pyqtgraph as pg

pg.setConfigOption('background','w') # Changes plot window background to white

####################

def tafin(a,b,c):       # function declaration
  window=pg.plot(title="Reflection") # Creates plot window called window
  Ax=linspace(-5,5)    # Generates values from -5 to 5
  Ay=-a*Ax/b-c/b       # Line equation
  window.plot(Ax,Ay)       # Plots line
  alpha=linspace(0,2*pi) # Generates alpha values
  Bx=cos(alpha)          # X coordinates of the (0,0) centered circumference 
  By=sin(alpha)          # Y coordinates of the (0,0) centered circumference 
  window.plot(Bx,By,pen='r') # Plots (0,0) centered circumference in red colour
  B1s=ones((1,size(Bx)))        # Line vector filled with 1's
  F=vstack((Bx,By,B1s)) # Compounds an array from Bx,By and B1s
  XA=0     # random point
  YA=(-a/b)*XA-(c/b)     # Obtains one point of the symetry line
  XB=1     # another random point
  YB=(-a/b)*XB-(c/b)     # Obtains another point of the symetry line
  # Symetry matrix
  Ta1=array(([XA,XB,-a],[YA,YB,-b],[1,1,0])) # Mirrored points coincident with line
  Ta2=linalg.inv(array(([XA,XB,a],[YA,YB,b],[1,1,0])))  # Original line coincident points
  Ta=dot(Ta1,Ta2) # Symetry matrix
  S=dot(Ta,F)     # Mirrors the circumference coordinates stored in F
  window.plot(S[0,:],S[1,:],pen='b') # Plots mirrored circumference in blue
  print "The affine transformation matix is"  #
  print Ta   # prints affine transformation matrix 



Open a terminal, paste the function and then type something like tafin(2.0,1.0,4.0)  the output should be very similar to the screenshot. 

Solving this problem with python has allowed me to understand more things about this language, for example, I used to import math as * alongside with numpy as *, this should not be done. The first thing where you can see how that affects to coding is the absence of "for" bucles to operate within arrays and their elements. 
This clearly makes the code easier, cleaner and more efficient and shorter than the matlab equivalent.

The new thing with the pyqtgraph module are the color plots, and plot background, easy to perform. 


With this problem I finish this little section about algebra and python, hope that you got something good from it. 

Bye!

No comments:

Post a Comment