Advertisement
Guest User

Untitled

a guest
Oct 24th, 2017
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.84 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Spyder Editor
  4.  
  5. This is a temporary script file.
  6. """
  7. import glob
  8. import os
  9. import sympy
  10. import re
  11.  
  12. path = 'C:\Users\Gebruiker\Documents\Radboud\Informatica\Jaar 2\Periode 1\Combinatoriek\ComputerAssignment'
  13.  
  14. import numpy as np
  15. from numpy.polynomial import Polynomial as P
  16. from numpy.linalg import solve, lstsq
  17.  
  18. def get_roots(poly):
  19. r = poly.r
  20. r = r[np.isreal(r)]
  21. r = [np.real(x) for x in r]
  22. m = [1 for i in range(0,len(r))]
  23. # calculate multiplicity using repeated differentiating
  24. # the derivative has multiplicity n-1
  25. while poly.o > 0:
  26. poly = np.polyder(poly)
  27. tmp = poly.r
  28. tmp = list(set(tmp[np.isreal(tmp)])) # use set to remove duplicates to avoid double counting
  29. for i in range(0,len(r)):
  30. for x in tmp:
  31. if(np.isclose(x,r[i])):
  32. m[i]+=1
  33. # remove duplicates in array, sometimes numpy puts roots multiple times
  34. if(len(r)==0):
  35. return r,m
  36. for x in range(0,len(r)-1):
  37. for y in range(x+1,len(r)):
  38. if(np.isclose(r[x],r[y])):
  39. m[x]+=1
  40. r[y]='x'
  41. m[y]='x'
  42. if 'x' in r:
  43. r.remove('x')
  44. if 'x' in m:
  45. m.remove('x')
  46. return r,m
  47.  
  48. def get_constants(r,m,initcond):
  49. rows = len(initcond)
  50. cols = np.sum(m)
  51. mat = np.empty([rows,cols])
  52. for n in range(0,len(initcond)):
  53. i = 0
  54. for k in range(0,len(r)):
  55. for l in range(0,m[k]):
  56. mat[n][i]=(n**l)*(r[k]**n)
  57. i+=1
  58. constants = lstsq(mat,initcond)[0] # lstsq instead of solve, which makes matrix linearly independent first
  59. return constants
  60.  
  61. def get_formula(r,m,constants):
  62. formula = ""
  63. i = 0
  64. for k in range(0,len(r)):
  65. formula+="("
  66. for l in range(0,m[k]):
  67. formula+=str(constants[i])
  68. if(l==1):
  69. +"*n"
  70. elif(l!=0):
  71. +"*n^"+str(l)
  72. if(l<m[k]-1):
  73. formula+="+"
  74. i+=1
  75. formula+=")*(" + str(r[k]) + ")^n"
  76. if(k<len(r)-1):
  77. formula+="+"
  78. return formula
  79.  
  80. def get_max_degree(receq):
  81. deg = 0
  82. for (x,y) in receq:
  83. if y > deg:
  84. deg = y
  85. return deg
  86.  
  87. #klopt niet:
  88. def get_characteristic(receq):
  89. deg = get_max_degree(receq)
  90. coef = []
  91. coef.append(1)
  92. for i in range(1,deg+1):
  93. a = 0
  94. for (x,y) in receq:
  95. if(y==i):
  96. a=x*(-1)
  97. coef.append(a)
  98. c = np.poly1d(coef)
  99. print(c)
  100. return c
  101.  
  102. def solve_homogenous(receq,initcond,debug=False):
  103. poly = get_characteristic(receq)
  104. r,m = get_roots(poly)
  105. constants = get_constants(r,m,initcond)
  106. if(debug):
  107. print "characteristic equation:"
  108. print poly
  109. print "roots:"
  110. print r
  111. print "multiplicities:"
  112. print m
  113. print "constants:"
  114. print constants
  115. print ""
  116. formula = get_formula(r,m,constants)
  117. return formula
  118.  
  119. def get_initcond(functions):
  120. initcond=[]
  121. for i in range (1, len(functions)):
  122. function = functions[i]
  123. ints = map(int, re.findall(r'-?\d*\.{0,1}\d', function)) #finds all integers \d+
  124. initcond.append(ints[1])
  125. return initcond
  126.  
  127. def get_receq(function):
  128. #if()
  129. receq = []
  130. index_s = [m.start() for m in re.finditer('s', function)]
  131. split_index = 0
  132. for i in range(0, len(index_s)):
  133. if(i==0):
  134. split_index = function.find(")",index_s[i])
  135. function_part = function[:split_index+1]
  136. elif(i==len(index_s)-1):
  137. function_part = function[split_index+1:]
  138. else:
  139. split_help = split_index+1
  140. split_index = function.find(")", split_index+1)
  141. function_part = function[split_help:split_index+1]
  142. ints = map(int, re.findall(r'-?\d*\.{0,1}\d', function_part))
  143. if (len(ints) == 1):
  144. if(function_part.find('s')==0):
  145. receq.append((1,ints[0]*-1))
  146. elif(function_part[function_part.find('s')-1] == '+'):
  147. receq.append((1,ints[0]*-1))
  148. elif(function_part[function_part.find('s')-1] == '-'):
  149. receq.append((-1,ints[0]*-1))
  150. else:
  151. receq.append((ints[0],ints[1]*-1))
  152. print(receq)
  153. return receq
  154.  
  155. #open file and split data
  156. for filename in glob.glob(os.path.join(path, 'comass??.txt')):
  157. homogenous = False
  158. exponential = False
  159. polynomial = False
  160. with open(filename,"r") as file:
  161. data = file.read() #put file data in data variable
  162. data = data[data.index("[")+1:] #remove the eqs[=] part of the string
  163. data = data[:data.index("]")]
  164. data = data.replace(" ","")
  165. functions = data.split(",") #put the seperate equations in an array
  166. functions[0] = functions[0][functions[0].index("=")+1:] #remove the s[n]= part from the rec eq
  167. hom = raw_input(functions[0] + str(' Is it homogenous, y or n?\n'))
  168. if(hom=="y"):
  169. homogenous = True
  170. else:
  171. exp = raw_input('Is it exponential, y or n?\n')
  172. if(exp=="y"):
  173. exponential = True
  174. poly = raw_input('Is it polynomial, y or n?\n')
  175. if(poly=="y"):
  176. polynomial = True
  177. if(homogenous):
  178. #initcond = [1,1] # [n0, n1, ... , nk]
  179. #receq = [(1,2),(1,1)] # (constant,degree)
  180. initcond=get_initcond(functions)
  181. receq = get_receq(functions[0])
  182. formula = solve_homogenous(receq,initcond,True)
  183.  
  184. print "formula:"
  185. print formula
  186.  
  187. #write the solution the right file:
  188. filename = filename[:-4] + str("-dir.txt")
  189. file = open(filename, "w")
  190. file.write("sdir := n -> " + str(formula))
  191. file.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement