Advertisement
morty0505

Untitled

Oct 9th, 2016
356
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.70 KB | None | 0 0
  1. import mandelbrot_1
  2. import mandelbrot_2
  3. import mandelbrot_3
  4.  
  5. import matplotlib.pyplot as plt
  6. import numpy as np
  7. import sys
  8.  
  9.  
  10. """Returns an array with the escape times for the provided rectangle,resotuion and max_escape_time
  11. If filename provided, a plot will be made, shown and saved"""
  12. def compute_mandelbrot(xmin,xmax,ymin,ymax,Nx,Ny,max_escape_time=1000,
  13.                         plot_filename=None,cur_cmap=plt.cm.prism,totime=False,
  14.                         mandel_func=mandelbrot_3.compute_mandelbrot):
  15.    
  16.     """
  17.     Checks if rectangle is outside mandelbrot set before iterations.
  18.     Checks if the circle that is made from abs(z) > 2, collides with the rectangle made from xmin,xmax,ymin,ymax
  19.    
  20.     Code based on : http://stackoverflow.com/a/21096179
  21.    
  22.     """
  23.     def is_not_outside(xmin,xmax,ymin,ymax):
  24.  
  25.         rect_x = xmin   #corner coordinate x
  26.         rect_y = ymin   #corner coordinate y
  27.         rect_w = abs(xmax-xmin) #width
  28.         rect_h = abs(ymax-ymin) #height
  29.        
  30.         #abs > 2 is a circle at 0,0 with radius 2
  31.         circle_x = 0
  32.         circle_y = 0
  33.         circle_radius = 2
  34.        
  35.         distX = abs(circle_x - rect_x - rect_w/2)
  36.         distY = abs(circle_y - rect_y - rect_h/2)
  37.        
  38.         dist_half_w = (rect_w/2 + circle_radius)
  39.         dist_half_h = (rect_h/2 + circle_radius)
  40.        
  41.         if (distX > dist_half_w) or (distY > dist_half_h) :
  42.             return False
  43.  
  44.         if (distX <= (rect_w/2)) or (distY <= (rect_h/2)):
  45.             return True
  46.  
  47.         dist_center_x = distX - rect_w/2
  48.         dist_center_y = distY - rect_h/2
  49.        
  50.         if dist_center_x**2 + dist_center_y**2 <= (circle_radius**2):
  51.             return True
  52.         else:
  53.             return False
  54.        
  55.  
  56.     if is_not_outside(xmin,xmax,ymin,ymax):
  57.         return mandel_func(xmin,xmax,ymin,ymax,Nx,Ny,max_escape_time,
  58.                         plot_filename,cur_cmap,totime)
  59.                        
  60.     else:
  61.         raise ValueError("Rectangle is entirely outstide the mandelbrot set. Invalid.")
  62.        
  63.        
  64.    
  65.  
  66. script_name = __file__
  67. usage_string = 'USAGE\t : ' + script_name + ' [rect=xmin,xmax,ymin,ymax] [res=Nx,Ny] [esc=INTEGER] [ver=1|2|3] [col=1|2|3] [out=FILENAME] [totime]'
  68.  
  69. """Prints usage output and exits execution"""
  70. def usage(error):
  71.     print(error)
  72.     print(usage_string)
  73.     print(script_name + ': try \'' + script_name + ' --help\' for more information')
  74.     sys.exit(0)
  75.    
  76. """Prints help information when called with --help. Exits after""" 
  77. def help():
  78.         print(usage_string)
  79.         print(' Explanation:')
  80.         # print()
  81.         print('  rect=xmin,xmax,ymin,ymax  : Sets rectangle to draw to [xmin,xmax] x [ymin,ymax] \n\tDefault : rect=-2,1,-1,-1')
  82.         print('  res=Nx,Ny                 : Sets resolution to Nx x Ny (both positive integers) \n\tDefault : 200 x 200')
  83.         print('  esc=INTEGER               : Sets max escape time provided integer \n\tDefault : 1000')
  84.         print('  ver=1|2|3                 : Choses impletation : 1 -> 4.1 , 2 -> 4.2 , 3 -> 4.3 \n\tDefault: 2 (4.2)')
  85.         print('  col=1|2|3                 : Choses color scale : 1 -> flag , 2 -> prism , 3 -> jet \n\tDefault: flag')
  86.         print('  out=FILENAME              : Filename to store the drawn image \n\tDefault: None')
  87.         print('  totime                    : Turns on printing of timing \n\tDefault: Set to False')
  88.         print('  test                      : Test-runs all the 3 implementations with timing \n\tDefault: Set to False')
  89.         sys.exit(0)
  90.  
  91.        
  92. def run_from_cmdline():
  93.  
  94.    
  95.     #default values
  96.     xmin = -2
  97.     xmax = 1
  98.     ymin = -1
  99.     ymax = 1
  100.     Nx = 400
  101.     Ny = 400
  102.     max_escape_time = 500
  103.     ver = 3
  104.     col = 1
  105.     plot_filename = None
  106.  
  107.     timeflag = False
  108.     testflag = False
  109.    
  110.     args = sys.argv[1:] #skip file name
  111.     for arg in args:
  112.         arg_split = arg.split('=')
  113.         try:
  114.             if arg == '--help':
  115.                 help()
  116.                
  117.             elif arg == 'totime':   #timing
  118.                 timeflag = True
  119.                 continue
  120.                
  121.             elif arg == 'test':     #added functionality
  122.                 testflag = True
  123.                 continue
  124.            
  125.             elif (len(arg_split) < 2):
  126.                 usage("Invalid input: " + arg)
  127.                
  128.             elif arg_split[0] == "rect":
  129.                 numbers_str = arg_split[1].split(',')
  130.                 xmin,xmax,ymin,ymax = [float(x) for x in numbers_str]
  131.                 if(xmin > xmax):
  132.                     usage("xmin >= xmax, invalid")
  133.                 if(ymin > ymax):
  134.                     usage("ymin >= ymax, invalid")
  135.                
  136.            
  137.             elif arg_split[0] == "res":
  138.                 numbers_str = arg_split[1].split(',')
  139.                 intvalNx,intvalNy = [int(x) for x in numbers_str]
  140.                 if intvalNx > 1 or intvalNy > 1:
  141.                     Nx = intvalNx
  142.                     Ny = intvalNy
  143.                 else:
  144.                     usage("resolution invalid : {},{} . Should be positive integers ".format(intvalNx,intvalNy))
  145.                    
  146.                    
  147.             elif arg_split[0] == "esc":
  148.                 intval = int(arg_split[1])
  149.                 if intval >= 1 :
  150.                     max_escape_time = intval
  151.                 else:
  152.                     usage("resolution invalid : {} . Should be positive integer ".format(intvalNx))
  153.                    
  154.             elif arg_split[0] == 'ver':
  155.                 intval = int(arg_split[1])
  156.                 if  (1 <= intval <= 3):
  157.                     ver = int(arg_split[1])
  158.                 else:
  159.                     usage("Implementation input invalid : {} . Should be 1,2 or 3 ".format(intval))
  160.                    
  161.             elif arg_split[0] == "out":
  162.                 plot_filename = arg_split[1]
  163.                
  164.             elif arg_split[0] == 'col':
  165.                 intval = int(arg_split[1])
  166.                 if  (1 <= intval <= 3):
  167.                     col = intval
  168.                 else:
  169.                     usage("Color scale invalid : {} . Should be 1,2 or 3 ".format(intval))
  170.            
  171.             else:
  172.                 usage('INVALID OPTION: ' + arg)
  173.                
  174.         except ValueError:
  175.             usage(arg_split[1] + " invalid input type or form for " + arg_split[0])
  176.         except IndexError:
  177.             usage(arg_split[1] + " : is not enough numbers in input for " + arg_split[0])
  178.  
  179.    
  180.    
  181.    
  182.     #set the function from right implementation
  183.     mandel_func =  mandelbrot_3.compute_mandelbrot      #default
  184.     if ver == 1:
  185.         mandel_func = mandelbrot_1.compute_mandelbrot
  186.     elif ver == 2:
  187.         mandel_func = mandelbrot_2.compute_mandelbrot
  188.  
  189.     #set the right color map
  190.     color_scale = plt.cm.flag               #default
  191.     color_scale.set_bad('black',1.)
  192.     if col == 2:
  193.         color_scale = plt.cm.prism
  194.         color_scale.set_bad('black',1.)
  195.     elif col == 3:
  196.         color_scale = plt.cm.jet
  197.  
  198.    
  199.    
  200.     if(not testflag):   #normal
  201.         compute_mandelbrot(xmin,xmax,ymin,ymax,Nx,Ny,max_escape_time,plot_filename,cur_cmap=color_scale,
  202.             totime=timeflag,mandel_func=mandel_func)
  203.     else:
  204.         #Runs timing for all 3 implementations and compares return-arrays
  205.         print("Testing all implementations")
  206.         print("args: ",Nx,Ny,xmin ,xmax, ymin ,ymax ,max_escape_time,ver,col)
  207.         a1 = mandelbrot_1.compute_mandelbrot(xmin,xmax,ymin,ymax,Nx,Ny,max_escape_time,None,cur_cmap=None,totime=True)
  208.         a2 = mandelbrot_2.compute_mandelbrot(xmin,xmax,ymin,ymax,Nx,Ny,max_escape_time,None,cur_cmap=None,totime=True)
  209.         a3 = mandelbrot_3.compute_mandelbrot(xmin,xmax,ymin,ymax,Nx,Ny,max_escape_time,None,cur_cmap=None,totime=True)
  210.         print("4.1 == 4.2 ->",np.array_equal(a1, a2))
  211.         print("4.1 == 4.3 ->",np.array_equal(a1, a3))
  212.         print("4.2 == 4.3 ->",np.array_equal(a2, a3))
  213.    
  214.    
  215.  
  216.    
  217.    
  218. if __name__ == "__main__":
  219.     try:
  220.         run_from_cmdline()
  221.     except ValueError as e: #catch ValueError if rectangle is enteriely outside from the start
  222.         print(e)
  223.         sys.exit(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement