Advertisement
Guest User

Untitled

a guest
May 29th, 2015
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. import sympy as s
  2. from sympy.interactive.printing import init_printing
  3. from sympy.matrices import Matrix
  4.  
  5. init_printing(use_unicode=False, wrap_line=False, no_global=True)
  6.  
  7. # In [1]: %load_ext autoreload
  8. #
  9. # In [2]: %autoreload 2
  10.  
  11. class Context(object):
  12. """some context where variables exists"""
  13. def __init__(self, size):
  14. self.numberOfVariables = size
  15. self.x = s.symbols('x:'+str(size))
  16. self.fn = None
  17. self.hessian = None
  18. self.detHessian = None
  19.  
  20. def setFn(self, expression):
  21. self.fn = expression
  22.  
  23. def getHessian(self):
  24.  
  25. expr = self.fn
  26.  
  27. hessianRows = []
  28. for idx in range(0, self.numberOfVariables):
  29.  
  30. hessianRow = []
  31.  
  32. diffWrt = s.diff(expr, self.x[idx])
  33.  
  34. for idx2ndDeriv in range(0, self.numberOfVariables):
  35.  
  36. hessianRow.append(s.diff(diffWrt, self.x[idx2ndDeriv]))
  37.  
  38. hessianRows.append(hessianRow)
  39.  
  40. self.hessian = Matrix(hessianRows)
  41.  
  42. return self.hessian
  43.  
  44. # compute the determinate of the hessian at point [x1 .. xn]
  45. def detHessianAt(self, subs):
  46.  
  47. if len(subs) != self.numberOfVariables:
  48.  
  49. raise Exception('airity mismatch: detHessianAt')
  50.  
  51. if self.hessian == None:
  52.  
  53. self.hessian = self.getHessian()
  54.  
  55. if self.detHessian == None:
  56.  
  57. self.detHessian = self.hessian.det()
  58.  
  59. detHessian = self.detHessian
  60.  
  61. for idx in range(0, self.numberOfVariables):
  62.  
  63. detHessian = detHessian.subs(self.x[idx], subs[idx]);
  64.  
  65. return detHessian
  66.  
  67.  
  68. def secondPartialTest(self, subs):
  69.  
  70. dValue = self.detHessianAt(subs).evalf()
  71.  
  72. if(dValue < 0):
  73.  
  74. return "Saddle Point at f(" + str(subs) + ")"
  75.  
  76. if(dValue == 0):
  77.  
  78. return "Inconclusive at f(" + str(subs) + ")"
  79.  
  80. # get the function at the top left of the hession
  81. secondDerivAtSub = self.hessian[0,0]
  82.  
  83. value = secondDerivAtSub
  84.  
  85. for idx in range(0, self.numberOfVariables):
  86.  
  87. value = value.subs(self.x[idx], subs[idx]);
  88.  
  89. value = value.evalf()
  90.  
  91. if value > 0:
  92.  
  93. return "Relative Minimum at f(" + str(subs) + ")"
  94.  
  95. if value < 0:
  96.  
  97. return "Relative Maximum at f(" + str(subs) + ")"
  98.  
  99.  
  100. c = Context(2)
  101.  
  102. # c.setFn((0.5 - c.x[0] ** 2 + c.x[1] ** 2) * (s.exp( 1 - c.x[0]**2 - c.x[1]**2 )))
  103. c.setFn( ( - c.x[0]**3 ) + ( 4*c.x[0]*c.x[1] ) - ( 2 * ( c.x[1] ** 2 ) ) + 1 )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement