PageRenderTime 63ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/pymaclab/dsge/solvers/modsolvers.py

https://github.com/TomAugspurger/pymaclab
Python | 2924 lines | 2868 code | 3 blank | 53 comment | 15 complexity | 95c7bd14fdd96ba23a8aac13e0e13496 MD5 | raw file
Possible License(s): Apache-2.0
  1. '''
  2. .. module:: modsolvers
  3. :platform: Linux
  4. :synopsis: The modsolvers module is an integral part of PyMacLab and is called extensively from the DSGEmodel class in module
  5. macrolab. It contains all of the dynamic solver methods most of which make use of the DSGE models' derivatives, i.e.
  6. the computed (numerical) Jacobian and Hessian.
  7. .. moduleauthor:: Eric M. Scheffel <eric.scheffel@nottingham.edu.cn>
  8. '''
  9. from numpy import matlib as MAT
  10. from numpy import linalg as LIN
  11. from numpy.linalg import matrix_rank
  12. from .. import helpers as HLP
  13. from scipy.linalg import qz
  14. import numpy as np
  15. import pylab as P
  16. from matplotlib import pyplot as PLT
  17. import copy as COP
  18. from pymaclab.filters import hpfilter
  19. from pymaclab.filters import bkfilter
  20. from pymaclab.filters import cffilter
  21. from isolab import isolab
  22. try:
  23. import mlabraw
  24. except:
  25. pass
  26. class MODsolvers(object):
  27. def __init__(self):
  28. pass
  29. class Dynare(object):
  30. def __init__(self,attdic):
  31. self.attdic = attdic
  32. for keyo in attdic.keys():
  33. self.__setattr__(keyo,COP.deepcopy(attdic[keyo]))
  34. class PyUhlig(MODsolvers):
  35. def __init__(self,intup):
  36. self.ntup = intup[0]
  37. self.nendo = self.ntup[0]
  38. self.ncon = self.ntup[1]
  39. self.nexo = self.ntup[2]
  40. self.eqindx = intup[1]
  41. self.vreg = intup[2]
  42. self.llsys_list = intup[3]
  43. self.diffli1 = intup[4]
  44. self.diffli2 = intup[5]
  45. diffli1 = self.diffli1
  46. diffli2 = self.diffli2
  47. deteq = []
  48. for x in self.eqindx['det']:
  49. deteq.append(self.llsys_list[x])
  50. self.deteq = deteq
  51. expeq = []
  52. for x in self.eqindx['exp']:
  53. expeq.append(self.llsys_list[x])
  54. self.expeq = expeq
  55. erreq = []
  56. for x in self.eqindx['err']:
  57. erreq.append(self.llsys_list[x])
  58. self.erreq = erreq
  59. detdif1 = []
  60. detdif2 = []
  61. for x in self.eqindx['det']:
  62. detdif1.append(diffli1[x])
  63. detdif2.append(diffli2[x])
  64. expdif1 = []
  65. expdif2 = []
  66. for x in self.eqindx['exp']:
  67. expdif1.append(diffli1[x])
  68. expdif2.append(diffli2[x])
  69. errdif1 = []
  70. errdif2 = []
  71. for x in self.eqindx['err']:
  72. errdif1.append(diffli1[x])
  73. errdif2.append(diffli2[x])
  74. self.detdif1 = detdif1
  75. self.detdif2 = detdif2
  76. self.expdif1 = expdif1
  77. self.expdif2 = expdif2
  78. self.errdif1 = errdif1
  79. self.errdif2 = errdif2
  80. self.mkmats()
  81. def mkmats(self):
  82. deteq = self.deteq
  83. expeq = self.expeq
  84. erreq = self.erreq
  85. nendo = self.nendo
  86. ncon = self.ncon
  87. nexo = self.nexo
  88. vreg = self.vreg
  89. detdif1 = self.detdif1
  90. detdif2 = self.detdif2
  91. expdif1 = self.expdif1
  92. expdif2 = self.expdif2
  93. errdif1 = self.errdif1
  94. errdif2 = self.errdif2
  95. # Create argument list for matrix creation
  96. argli = [['AA',(detdif2,detdif1),deteq,(len(deteq),nendo),(None,'endo','0')],
  97. ['BB',(detdif2,detdif1),deteq,(len(deteq),nendo),(None,'endo','-1')],
  98. ['CC',(detdif2,detdif1),deteq,(len(deteq),ncon),(None,'con','0')],
  99. ['DD',(detdif2,detdif1),deteq,(len(deteq),nexo),(None,'exo','0')],
  100. ['FF',(expdif2,expdif1),expeq,(len(expeq),nendo),('0','endo','1')],
  101. ['GG',(expdif2,expdif1),expeq,(len(expeq),nendo),(None,'endo','0')],
  102. ['HH',(expdif2,expdif1),expeq,(len(expeq),nendo),(None,'endo','-1')],
  103. ['JJ',(expdif2,expdif1),expeq,(len(expeq),ncon),('0','con','1')],
  104. ['KK',(expdif2,expdif1),expeq,(len(expeq),ncon),(None,'con','0')],
  105. ['LL',(expdif2,expdif1),expeq,(len(expeq),nexo),('0','exo','1')],
  106. ['MM',(expdif2,expdif1),expeq,(len(expeq),nexo),(None,'exo','0')],
  107. ['NN',(errdif2,errdif1),erreq,(len(erreq),nexo),(None,'exo','0')]]
  108. # Create all matrices in a loop over argli
  109. for argx in argli:
  110. XX = MAT.zeros(argx[3])
  111. dic1 = dict([[x,'0'] for x in range(argx[3][1])])
  112. sXX = dict([[x,COP.deepcopy(dic1)] for x in range(len(argx[2]))])
  113. for y,x in enumerate(argx[2]):
  114. if vreg(argx[4],x,False,'max'):
  115. cont=[[z[0],z[1][1]] for z in vreg(argx[4],x,True,'min')]
  116. for z in cont:
  117. XX[y,z[1]] = argx[1][0][y][z[0]]
  118. sXX[y][z[1]] = argx[1][1][y][z[0]]
  119. exec('self.'+argx[0]+' = XX')
  120. exec('self.'+'s'+argx[0]+' = sXX')
  121. def solve(self,sol_method='do_QZ',Xi_select='all'):
  122. self.output = {}
  123. self.Xi_select = Xi_select
  124. self.sol_method = sol_method
  125. if self.sol_method == 'do_PP':
  126. self.do_PP(self.Xi_select)
  127. elif self.sol_method == 'do_QZ':
  128. self.do_QZ(self.Xi_select,Tol=1.0000e-06)
  129. self.do_QRS()
  130. def do_QZ(self,Xi_select='all',Tol=1.0000e-06):
  131. # Make uhlig matrices locally available for computations
  132. AA = self.AA
  133. BB = self.BB
  134. CC = self.CC
  135. DD = self.DD
  136. FF = self.FF
  137. GG = self.GG
  138. HH = self.HH
  139. JJ = self.JJ
  140. KK = self.KK
  141. LL = self.LL
  142. MM = self.MM
  143. NN = self.NN
  144. q_expectational_equ = np.shape(FF)[0]
  145. m_states = np.shape(FF)[1]
  146. l_equ = np.shape(CC)[0]
  147. n_endog = np.shape(CC)[1]
  148. k_exog = min(np.shape(NN))
  149. # if HLP.rank(CC) < n_endog:
  150. if matrix_rank(CC) < n_endog:
  151. raise uhlerr, 'uhlerror: Rank(CC) needs to be at least\n\
  152. equal to the number of endogenous variables'
  153. if l_equ == 0:
  154. CC_plus = LIN.pinv(CC)
  155. CC_0 = (HLP.null(CC.T)).T
  156. Psi_mat = FF
  157. Gamma_mat = -GG
  158. Theta_mat = -HH
  159. Xi_mat = \
  160. np.concatenate((Gamma_mat,Theta_mat,MAT.eye(m_states),\
  161. MAT.zeros((m_states,m_states))),1)
  162. Delta_mat = \
  163. np.concatenate((Psi_mat,MAT.zeros((m_states,m_states)),\
  164. MAT.zeros((m_states,m_states)),\
  165. MAT.zeros((m_states,m_states)),MAT.eye(m_states),1))
  166. else:
  167. CC_plus = LIN.pinv(CC)
  168. CC_0 = HLP.null(CC.T)
  169. if l_equ > n_endog:
  170. Psi_mat = \
  171. np.concatenate((MAT.zeros((l_equ-n_endog,m_states)),FF-JJ*CC_plus*AA),1)
  172. elif l_equ == n_endog:
  173. Psi_mat = np.concatenate((FF-JJ*CC_plus*AA),1)
  174. Gamma_mat = np.concatenate((CC_0*AA, JJ*CC_plus*BB-GG+KK*CC_plus*AA))
  175. Theta_mat = np.concatenate((CC_0*BB, KK*CC_plus*BB-HH))
  176. Xi_mat = \
  177. np.concatenate((\
  178. np.concatenate((Gamma_mat,Theta_mat),1),\
  179. np.concatenate((MAT.identity(m_states),MAT.zeros((m_states,m_states))),1)\
  180. ))
  181. Psi_mat = Psi_mat.reshape(m_states,m_states)
  182. Delta_mat = \
  183. np.concatenate((\
  184. np.concatenate((Psi_mat,MAT.zeros((m_states,m_states))),1),\
  185. np.concatenate((MAT.zeros((m_states,m_states)),MAT.identity(m_states)),1)\
  186. ))
  187. # (Delta_up,Xi_up,UUU,VVV)=\
  188. # HLP.qz(Delta_mat,Xi_mat,\
  189. # mode='complex',\
  190. # lapackname=lapackname,\
  191. # lapackpath=lapackpath)
  192. (Delta_up,Xi_up,UUU,VVV) = qz(Delta_mat,Xi_mat)
  193. d_Delta_up = MAT.diag(Delta_up)
  194. d_Xi_up = MAT.diag(Xi_up)
  195. Xi_eigval = MAT.zeros(N.shape(Delta_up))
  196. for i1 in range(0,N.shape(Delta_up)[0],1):
  197. Xi_eigval[i1,i1] = d_Xi_up[i1]/d_Delta_up[i1]
  198. d_Xi_eigval = np.diag(Xi_eigval)
  199. mat_tmp = MAT.zeros((N.shape(Xi_eigval)[0],3))
  200. i1=0
  201. for x in d_Xi_eigval:
  202. mat_tmp[i1,0] = d_Xi_eigval[i1]
  203. mat_tmp[i1,1] = abs(d_Xi_eigval)[i1]
  204. mat_tmp[i1,2] = i1
  205. i1=i1+1
  206. Xi_sortval = HLP.sortrows(mat_tmp,1)[:,0]
  207. # Need to do an argsort() on index column to turn to integers (Booleans) !!
  208. Xi_sortindex = HLP.sortrows(mat_tmp,1)[:,2].argsort(axis=0)
  209. Xi_sortabs = HLP.sortrows(mat_tmp,1)[:,1]
  210. # Root selection branch with Xi_select
  211. if Xi_select == 'all':
  212. Xi_select = np.arange(0,m_states,1)
  213. stake = max(abs(Xi_sortval[Xi_select])) + Tol
  214. (Delta_up,Xi_up,UUU,VVV) = self.qzdiv(stake,Delta_up,Xi_up,UUU,VVV)
  215. Lamda_mat = np.diag(Xi_sortval[Xi_select])
  216. trVVV = VVV.conjugate().T
  217. VVV_2_1 = trVVV[m_states:2*m_states,0:m_states]
  218. VVV_2_2 = trVVV[m_states:2*m_states,m_states:2*m_states]
  219. UUU_2_1 = UUU[m_states:2*m_states,0:m_states]
  220. PP = -(VVV_2_1.I*VVV_2_2)
  221. PP = np.real(PP)
  222. self.PP = PP
  223. self.CC_plus = CC_plus
  224. def do_PP(self,Xi_select='all'):
  225. # Make uhlig matrices locally available for computations
  226. AA = self.AA
  227. BB = self.BB
  228. CC = self.CC
  229. DD = self.DD
  230. FF = self.FF
  231. GG = self.GG
  232. HH = self.HH
  233. JJ = self.JJ
  234. KK = self.KK
  235. LL = self.LL
  236. MM = self.MM
  237. NN = self.NN
  238. q_expectational_equ = np.shape(FF)[0]
  239. m_states = np.shape(FF)[1]
  240. l_equ = np.shape(CC)[0]
  241. n_endog = np.shape(CC)[1]
  242. k_exog = min(N.shape(NN))
  243. # if HLP.rank(CC) < n_endog:
  244. if matrix_rank(CC) < n_endog:
  245. raise uhlerr, 'uhlerror: Rank(CC) needs to be at least\n\
  246. equal to the number of endogenous variables'
  247. if l_equ == 0:
  248. CC_plus = LIN.pinv(CC)
  249. CC_0 = (HLP.null(CC.T)).T
  250. Psi_mat = FF
  251. Gamma_mat = -GG
  252. Theta_mat = -HH
  253. Xi_mat = \
  254. np.concatenate((Gamma_mat,Theta_mat,MAT.eye(m_states),\
  255. MAT.zeros((m_states,m_states))),1)
  256. Delta_mat = \
  257. np.concatenate((Psi_mat,MAT.zeros((m_states,m_states)),\
  258. MAT.zeros((m_states,m_states)),\
  259. MAT.zeros((m_states,m_states)),MAT.eye(m_states),1))
  260. else:
  261. CC_plus = LIN.pinv(CC)
  262. CC_0 = HLP.null(CC.T)
  263. if l_equ > n_endog:
  264. Psi_mat = \
  265. np.concatenate((MAT.zeros((l_equ-n_endog,m_states)),FF-JJ*CC_plus*AA),1)
  266. elif l_equ == n_endog:
  267. Psi_mat = np.concatenate((FF-JJ*CC_plus*AA),1)
  268. Gamma_mat = np.concatenate((CC_0*AA, JJ*CC_plus*BB-GG+KK*CC_plus*AA))
  269. Theta_mat = np.concatenate((CC_0*BB, KK*CC_plus*BB-HH))
  270. Xi_mat = \
  271. np.concatenate((\
  272. np.concatenate((Gamma_mat,Theta_mat),1),\
  273. np.concatenate((MAT.eye(m_states),MAT.zeros((m_states,m_states))),1)\
  274. ))
  275. Delta_mat = \
  276. np.concatenate((\
  277. np.concatenate((Psi_mat,MAT.zeros((m_states,m_states))),1),\
  278. np.concatenate((MAT.zeros((m_states,m_states)),MAT.eye(m_states)),1)\
  279. ))
  280. (Xi_eigvec,Xi_eigval) = HLP.eig(Xi_mat,Delta_mat)
  281. tmp_mat = MAT.eye(N.rank(Xi_eigvec))
  282. for i1 in range(0,N.rank(Xi_eigvec),1):
  283. tmp_mat[i1,i1] = float(Xi_eigval[0,i1])
  284. Xi_eigval = tmp_mat
  285. # if HLP.rank(Xi_eigvec) < m_states:
  286. if matrix_rank(Xi_eigvec) < m_states:
  287. raise uhlerr, 'uhlerror: Xi_mat is not diagonalizable!\n\
  288. Cannot solve for PP. Maybe you should try the Schur-Decomposition\n\
  289. method instead, use do_QZ()!!'
  290. d_Xi_eigval = np.diag(Xi_eigval)
  291. mat_tmp = MAT.zeros((N.rank(Xi_eigval),3))
  292. i1=0
  293. for x in d_Xi_eigval:
  294. mat_tmp[i1,0] = d_Xi_eigval[i1]
  295. mat_tmp[i1,1] = abs(d_Xi_eigval[i1])
  296. mat_tmp[i1,2] = i1
  297. i1=i1+1
  298. Xi_sortval = HLP.sortrows(mat_tmp,1)[:,0]
  299. # Need to do an argsort() on index column to turn to integers (Booleans) !!
  300. Xi_sortindex = HLP.sortrows(mat_tmp,1)[:,2].argsort(axis=0)
  301. Xi_sortabs = HLP.sortrows(mat_tmp,1)[:,1]
  302. Xi_sortvec = Xi_eigvec[0:2*m_states,:].take(Xi_sortindex.T.A, axis=1)
  303. # Root selection branch with Xi_select
  304. if Xi_select == 'all':
  305. Xi_select = np.arange(0,m_states,1)
  306. #Create Lambda_mat and Omega_mat
  307. Lambda_mat = MAT.zeros((len(Xi_select),len(Xi_select)))
  308. for i1 in range(0,len(Xi_select),1):
  309. Lambda_mat[i1,i1] = Xi_sortval[Xi_select][i1]
  310. Omega_mat = Xi_sortvec[m_states:2*m_states,:].take(Xi_select, axis=1)
  311. # if HLP.rank(Omega_mat) < m_states:
  312. if matrix_rank(Omega_mat) < m_states:
  313. raise uhlerr, 'uhlerror: Omega_mat is not invertible!!\n\
  314. Therefore, solution for PP is not available'
  315. PP = Omega_mat*HLP.ctr((HLP.ctr(Omega_mat).I*HLP.ctr(Lambda_mat)))
  316. self.PP = PP
  317. self.CC_plus = CC_plus
  318. def do_QRS(self):
  319. # Make uhlig matrices locally available for computations
  320. AA = self.AA
  321. BB = self.BB
  322. CC = self.CC
  323. DD = self.DD
  324. FF = self.FF
  325. GG = self.GG
  326. HH = self.HH
  327. JJ = self.JJ
  328. KK = self.KK
  329. LL = self.LL
  330. MM = self.MM
  331. NN = self.NN
  332. PP = self.PP
  333. CC_plus = self.CC_plus
  334. (l_equ,m_states) = MAT.shape(AA)
  335. (l_equ,n_endog) = MAT.shape(CC)
  336. (l_equ,k_exog) = MAT.shape(DD)
  337. if l_equ == 0:
  338. RR = MAT.zeros((0,m_states))
  339. VV1 = MAT.kron(MAT.transpose(NN),FF)+MAT.kron(MAT.identity(k_exog),FF*PP+GG)
  340. VV2 = MAT.kron(MAT.transpose(NN),JJ)+MAT.kron(MAT.identity(k_exog),KK)
  341. VV = MAT.hstack((VV1,VV2))
  342. else:
  343. RR = -CC_plus*(AA*PP+BB)
  344. VV1 = MAT.kron(MAT.identity(k_exog),AA)
  345. VV2 = MAT.kron(MAT.identity(k_exog),CC)
  346. VV3 = MAT.kron(MAT.transpose(NN),FF)+MAT.kron(MAT.identity(k_exog),FF*PP+JJ*RR+GG)
  347. VV4 = MAT.kron(MAT.transpose(NN),JJ)+MAT.kron(MAT.identity(k_exog),KK)
  348. VV = MAT.vstack((MAT.hstack((VV1,VV2)),MAT.hstack((VV3,VV4))))
  349. self.RR = RR
  350. LLNN_plus_MM = LL*NN+MM
  351. NON = MAT.hstack((DD.flatten(1),LLNN_plus_MM.flatten(1)))
  352. try:
  353. QQSS_vec = -(VV.I*MAT.transpose(NON))
  354. except MyErr:
  355. print 'Error: Matrix VV is not invertible!'
  356. QQ = QQSS_vec[0:m_states*k_exog,:].reshape(-1,m_states).transpose()
  357. SS = QQSS_vec[(m_states*k_exog):((m_states+n_endog)*k_exog),:].reshape(-1,n_endog).transpose()
  358. WW1 = MAT.hstack((MAT.identity(m_states),MAT.zeros((m_states,k_exog))))
  359. WW2 = MAT.hstack((RR*LIN.pinv(PP),SS-RR*LIN.pinv(PP)*QQ))
  360. WW3 = MAT.hstack((MAT.zeros((k_exog,m_states)),MAT.identity(k_exog)))
  361. WW = MAT.vstack((WW1,WW2,WW3))
  362. self.WW = WW
  363. self.QQ = QQ
  364. self.SS = SS
  365. del self.CC_plus
  366. def qzdiv(self,stake,A,B,Q,Z):
  367. n = np.shape(A)[0]
  368. root = np.hstack((abs(N.mat(N.diag(A)).T),abs(N.mat(N.diag(B)).T)))
  369. index_mat = (root[:,0]<1e-13).choose(root[:,0],1)
  370. index_mat = (index_mat>1e-13).choose(root[:,0],0)
  371. root[:,0] = root[:,0]-MAT.multiply(index_mat,(root[:,0]+root[:,1]))
  372. root[:,1] = root[:,1]/root[:,0]
  373. for i1 in range(n-1,-1,-1):
  374. m='none'
  375. for i2 in range(i1,-1,-1):
  376. if root[i2,1] > stake or root[i2,1] < -0.1:
  377. m=i2
  378. break
  379. if m == 'none':
  380. return (A,B,Q,Z)
  381. else:
  382. for i3 in range(m,i1,1):
  383. (A,B,Q,Z) = self.qzswitch(i3,A,B,Q,Z)
  384. tmp = COP.deepcopy(root[i3,1])
  385. root[i3,1] = root[i3+1,1]
  386. root[i3+1,1] = tmp
  387. def qzswitch(self,i,A,B,Q,Z):
  388. a = A[i,i]
  389. d = B[i,i]
  390. b = A[i,i+1]
  391. e = B[i,i+1]
  392. c = A[i+1,i+1]
  393. f = B[i+1,i+1]
  394. wz = np.mat(N.hstack(((c*e-f*b),(c*d-f*a).conjugate().T)))
  395. xy = np.mat(N.hstack(((b*d-e*a).conjugate().T,(c*d-f*a).conjugate().T)))
  396. n = np.mat(N.sqrt(wz*wz.conjugate().T))
  397. m = np.mat(N.sqrt(xy*xy.conjugate().T))
  398. if n.all() == 0:
  399. return
  400. else:
  401. wz = np.mat(wz/n)
  402. xy = np.mat(xy/m)
  403. wz = np.vstack((wz,N.hstack((-wz[:,1].T,wz[:,0].T))))
  404. xy = np.vstack((xy,N.hstack((-xy[:,1].T,xy[:,0].T))))
  405. A[i:i+2,:] = xy*A[i:i+2,:]
  406. B[i:i+2,:] = xy*B[i:i+2,:]
  407. A[:,i:i+2] = A[:,i:i+2]*wz
  408. B[:,i:i+2] = B[:,i:i+2]*wz
  409. Z[:,i:i+2] = Z[:,i:i+2]*wz
  410. Q[i:i+2,:] = xy*Q[i:i+2,:]
  411. return (A,B,Q,Z)
  412. #----------------------------------------------------------------------------------------------------------------------
  413. class MatUhlig:
  414. def __init__(self,intup):
  415. self.ntup = intup[0]
  416. self.nendo = self.ntup[0]
  417. self.ncon = self.ntup[1]
  418. self.nexo = self.ntup[2]
  419. self.eqindx = intup[1]
  420. self.vreg = intup[2]
  421. self.llsys_list = intup[3]
  422. self.diffli1 = intup[4]
  423. self.diffli2 = intup[5]
  424. self.sess1 = intup[6]
  425. self.vardic = intup[7]
  426. diffli1 = self.diffli1
  427. diffli2 = self.diffli2
  428. deteq = []
  429. for x in self.eqindx['det']:
  430. deteq.append(self.llsys_list[x])
  431. self.deteq = deteq
  432. expeq = []
  433. for x in self.eqindx['exp']:
  434. expeq.append(self.llsys_list[x])
  435. self.expeq = expeq
  436. erreq = []
  437. for x in self.eqindx['err']:
  438. erreq.append(self.llsys_list[x])
  439. self.erreq = erreq
  440. detdif1 = []
  441. detdif2 = []
  442. for x in self.eqindx['det']:
  443. detdif1.append(diffli1[x])
  444. detdif2.append(diffli2[x])
  445. expdif1 = []
  446. expdif2 = []
  447. for x in self.eqindx['exp']:
  448. expdif1.append(diffli1[x])
  449. expdif2.append(diffli2[x])
  450. errdif1 = []
  451. errdif2 = []
  452. for x in self.eqindx['err']:
  453. errdif1.append(diffli1[x])
  454. errdif2.append(diffli2[x])
  455. self.detdif1 = detdif1
  456. self.detdif2 = detdif2
  457. self.expdif1 = expdif1
  458. self.expdif2 = expdif2
  459. self.errdif1 = errdif1
  460. self.errdif2 = errdif2
  461. self.mkmats()
  462. def mkmats(self):
  463. deteq = self.deteq
  464. expeq = self.expeq
  465. erreq = self.erreq
  466. nendo = self.nendo
  467. ncon = self.ncon
  468. nexo = self.nexo
  469. vreg = self.vreg
  470. detdif1 = self.detdif1
  471. detdif2 = self.detdif2
  472. expdif1 = self.expdif1
  473. expdif2 = self.expdif2
  474. errdif1 = self.errdif1
  475. errdif2 = self.errdif2
  476. # Create argument list for matrix creation
  477. argli = [['AA',(detdif2,detdif1),deteq,(len(deteq),nendo),(None,'endo','0')],
  478. ['BB',(detdif2,detdif1),deteq,(len(deteq),nendo),(None,'endo','-1')],
  479. ['CC',(detdif2,detdif1),deteq,(len(deteq),ncon),(None,'con','0')],
  480. ['DD',(detdif2,detdif1),deteq,(len(deteq),nexo),(None,'exo','0')],
  481. ['FF',(expdif2,expdif1),expeq,(len(expeq),nendo),('0','endo','1')],
  482. ['GG',(expdif2,expdif1),expeq,(len(expeq),nendo),(None,'endo','0')],
  483. ['HH',(expdif2,expdif1),expeq,(len(expeq),nendo),(None,'endo','-1')],
  484. ['JJ',(expdif2,expdif1),expeq,(len(expeq),ncon),('0','con','1')],
  485. ['KK',(expdif2,expdif1),expeq,(len(expeq),ncon),(None,'con','0')],
  486. ['LL',(expdif2,expdif1),expeq,(len(expeq),nexo),('0','exo','1')],
  487. ['MM',(expdif2,expdif1),expeq,(len(expeq),nexo),(None,'exo','0')],
  488. ['NN',(errdif2,errdif1),erreq,(len(erreq),nexo),(None,'exo','0')]]
  489. # Create all matrices in a loop over argli
  490. for argx in argli:
  491. XX = MAT.zeros(argx[3])
  492. dic1 = dict([[x,'0'] for x in range(argx[3][1])])
  493. sXX = dict([[x,COP.deepcopy(dic1)] for x in range(len(argx[2]))])
  494. for y,x in enumerate(argx[2]):
  495. if vreg(argx[4],x,False,'max'):
  496. cont=[[z[0],z[1][1]] for z in vreg(argx[4],x,True,'min')]
  497. for z in cont:
  498. XX[y,z[1]] = argx[1][0][y][z[0]]
  499. sXX[y][z[1]] = argx[1][1][y][z[0]]
  500. exec('self.'+argx[0]+' = XX')
  501. exec('self.'+'s'+argx[0]+' = sXX')
  502. def solve(self,sol_method='do_QZ',Xi_select='all'):
  503. # Create varnames with correct string length
  504. tmp_list =[x[1] for x in self.vardic['endo']['var']]\
  505. +[x[1] for x in self.vardic['con']['var']]\
  506. +[x[1] for x in self.vardic['exo']['var']]
  507. tmp_list2 = [[len(x),x] for x in tmp_list]
  508. tmp_list2.sort()
  509. max_len = tmp_list2[-1][0]
  510. i1=0
  511. for x in tmp_list:
  512. tmp_list[i1]=x+(max_len-len(x))*' '
  513. i1=i1+1
  514. varnstring = 'VARNAMES = ['
  515. for x in tmp_list:
  516. varnstring = varnstring + "'" +x[1]+ "'" + ','
  517. varnstring = varnstring[0:-1]+'];'
  518. # Start matlab session and calculate
  519. sess1 = self.sess1
  520. mlabraw.eval(sess1,'clear all;')
  521. mlabraw.eval(sess1,varnstring)
  522. mlabraw.put(sess1,'AA',self.AA)
  523. mlabraw.put(sess1,'BB',self.BB)
  524. mlabraw.put(sess1,'CC',self.CC)
  525. mlabraw.put(sess1,'DD',self.DD)
  526. mlabraw.put(sess1,'FF',self.FF)
  527. mlabraw.put(sess1,'GG',self.GG)
  528. mlabraw.put(sess1,'HH',self.HH)
  529. mlabraw.put(sess1,'JJ',self.JJ)
  530. mlabraw.put(sess1,'KK',self.KK)
  531. mlabraw.put(sess1,'LL',self.LL)
  532. mlabraw.put(sess1,'MM',self.MM)
  533. mlabraw.put(sess1,'NN',self.NN)
  534. mlabraw.eval(sess1,'cd '+mlabpath)
  535. mlabraw.eval(sess1,'cd Toolkit41')
  536. message = ' '*70
  537. eval_list = ['message='+"'"+message+"'",
  538. 'warnings = [];',
  539. 'options;',
  540. 'solve;']
  541. try:
  542. for x in eval_list:
  543. mlabraw.eval(sess1,x)
  544. self.PP = np.matrix(mlabraw.get(sess1,'PP'))
  545. self.QQ = np.matrix(mlabraw.get(sess1,'QQ'))
  546. self.RR = np.matrix(mlabraw.get(sess1,'RR'))
  547. self.SS = np.matrix(mlabraw.get(sess1,'SS'))
  548. self.WW = np.matrix(mlabraw.get(sess1,'WW'))
  549. except MyErr:
  550. pass
  551. finally:
  552. return
  553. #----------------------------------------------------------------------------------------------------------------------
  554. class MatKlein:
  555. def __init__(self,intup):
  556. self.sess1 = intup[-1]
  557. self.uhlig = PyUhlig(intup[:-1])
  558. self.uhlig.mkmats()
  559. self.AA = self.uhlig.AA
  560. self.BB = self.uhlig.BB
  561. self.CC = self.uhlig.CC
  562. self.DD = self.uhlig.DD
  563. self.FF = self.uhlig.FF
  564. self.GG = self.uhlig.GG
  565. self.HH = self.uhlig.HH
  566. self.JJ = self.uhlig.JJ
  567. self.KK = self.uhlig.KK
  568. self.LL = self.uhlig.LL
  569. self.MM = self.uhlig.MM
  570. self.NN = self.uhlig.NN
  571. self.mkKleinMats()
  572. self.outdic = {}
  573. def mkKleinMats(self):
  574. # Make uhlig matrices locally available for computations
  575. AA = self.AA
  576. BB = self.BB
  577. CC = self.CC
  578. DD = self.DD
  579. FF = self.FF
  580. GG = self.GG
  581. HH = self.HH
  582. JJ = self.JJ
  583. KK = self.KK
  584. LL = self.LL
  585. MM = self.MM
  586. NN = self.NN
  587. # Determine size of states, endogenous
  588. exo_st = MAT.shape(NN)[1]
  589. endo_st = MAT.shape(BB)[1]
  590. endo_cn = MAT.shape(CC)[1]
  591. n_deteq = MAT.shape(AA)[0]
  592. n_expeq = MAT.shape(JJ)[0]
  593. tot_st = exo_st+endo_st
  594. self.tstates = tot_st
  595. tot_var = tot_st+endo_cn
  596. klein_A_rtwo = MAT.hstack((LL,GG))
  597. klein_A_rtwo = MAT.hstack((klein_A_rtwo,JJ))
  598. klein_A_rtwo_rows = MAT.shape(klein_A_rtwo)[0]
  599. klein_A_rtwo_cols = MAT.shape(klein_A_rtwo)[1]
  600. klein_A_rone = MAT.zeros((exo_st,klein_A_rtwo_cols))
  601. klein_A_rone = MAT.hstack((MAT.identity(exo_st),klein_A_rone[:,exo_st:]))
  602. klein_A_rthree = MAT.hstack((MAT.zeros((n_deteq,exo_st)),AA))
  603. klein_A_rthree = MAT.hstack((klein_A_rthree,MAT.zeros((n_deteq,endo_cn))))
  604. klein_A = MAT.vstack((klein_A_rone,klein_A_rtwo))
  605. klein_A = MAT.vstack((klein_A,klein_A_rthree))
  606. klein_B_rone = MAT.zeros((exo_st,klein_A_rtwo_cols))
  607. klein_B_rone = MAT.hstack((NN,klein_B_rone[:,exo_st:]))
  608. klein_B_rtwo = MAT.hstack((-MM,-HH))
  609. klein_B_rtwo = MAT.hstack((klein_B_rtwo,-KK))
  610. klein_B_rthree = MAT.hstack((-DD,-BB))
  611. klein_B_rthree = MAT.hstack((klein_B_rthree,-CC))
  612. klein_B = MAT.vstack((klein_B_rone,klein_B_rtwo))
  613. klein_B = MAT.vstack((klein_B,klein_B_rthree))
  614. self.A = klein_A
  615. self.B = klein_B
  616. def solve(self):
  617. A = self.A
  618. B = self.B
  619. tstates = self.tstates
  620. sess1 = self.sess1
  621. mlabraw.eval(sess1,'clear all;')
  622. mlabraw.eval(sess1,'cd '+mlabpath)
  623. mlabraw.eval(sess1,'cd Klein')
  624. mlabraw.put(sess1,'AA',A)
  625. mlabraw.put(sess1,'BB',B)
  626. mlabraw.put(sess1,'tstates',tstates)
  627. try:
  628. mlabraw.eval(sess1,'[F,P,Z11]=solab(AA,BB,tstates)')
  629. self.F = np.matrix(mlabraw.get(sess1,'F'))
  630. self.P = np.matrix(mlabraw.get(sess1,'P'))
  631. self.Z11 = np.matrix(mlabraw.get(sess1,'Z11'))
  632. self.outdic['P'] = self.P
  633. self.outdic['F'] = self.F
  634. except MyErr:
  635. pass
  636. finally:
  637. return
  638. #----------------------------------------------------------------------------------------------------------------------
  639. class MatKleinD:
  640. def __init__(self,intup):
  641. self.interm3 = intup[0]
  642. self.param = intup[1]
  643. self.sstate_list = intup[2]
  644. self.varvecs = intup[3]
  645. self.vardic = intup[4]
  646. self.vardic2 = intup[5]
  647. self.shockdic = intup[6]
  648. self.shockdic2 = intup[7]
  649. self.varns = intup[8]
  650. self.re_var = intup[9]
  651. self.re_var2 = intup[10]
  652. self.ishockdic = intup[11]
  653. self.ishockdic2 = intup[12]
  654. self.sess1 = intup[13]
  655. self.sstate = intup[14]
  656. self.mkeqs()
  657. self.mkvarl()
  658. self.mkeqs2()
  659. self.mkgrad()
  660. self.mkAB()
  661. self.solab()
  662. self.mkhess()
  663. self.solab2()
  664. def mkeqs(self):
  665. list_tmp = COP.deepcopy(self.interm3)
  666. reg2 = RE.compile('\*{2,2}')
  667. reva2 = self.re_var2
  668. i1=0
  669. for x in list_tmp:
  670. list_tmp[i1]=reg2.sub('^',x.split('=')[0]).strip()
  671. for y in self.subvars(tuple(self.varvecs['e'])):
  672. while y in list_tmp[i1]:
  673. list_tmp[i1] = list_tmp[i1].replace(y,'1')
  674. i1=i1+1
  675. self.interm4 = list_tmp
  676. def mkvarl(self):
  677. varlist=[]
  678. nexost = len(self.varvecs['z'])
  679. nendost = len(self.varvecs['k'])
  680. nendocon = len(self.varvecs['y'])
  681. exost_f = makeForward(self.varvecs['z'],'1','0')
  682. for x in exost_f:
  683. varlist.append(x)
  684. for x in self.varvecs['k']:
  685. varlist.append(x)
  686. endocons_f = makeForward(self.varvecs['y'],'1','0')
  687. for x in endocons_f:
  688. varlist.append(x)
  689. exost_l = self.varvecs['z']
  690. for x in exost_l:
  691. varlist.append(x)
  692. endost_l = makeLags(self.varvecs['k'],'1')
  693. for x in endost_l:
  694. varlist.append(x)
  695. for x in self.varvecs['y']:
  696. varlist.append(x)
  697. varlist2 = list(self.subvars(tuple(varlist)))
  698. self.vlist = varlist2
  699. varlist=[]
  700. for x in self.varvecs['z']:
  701. varlist.append(x)
  702. for x in self.varvecs['k']:
  703. varlist.append(x)
  704. endocons_f = makeForward(self.varvecs['y'],'1','0')
  705. for x in endocons_f:
  706. varlist.append(x)
  707. exost_l = makeLags(self.varvecs['z'],'1')
  708. for x in exost_l:
  709. varlist.append(x)
  710. endost_l = makeLags(self.varvecs['k'],'1')
  711. for x in endost_l:
  712. varlist.append(x)
  713. for x in self.varvecs['y']:
  714. varlist.append(x)
  715. varlist2 = list(self.subvars(tuple(varlist)))
  716. self.vlist2 = varlist2
  717. def mkeqs2(self):
  718. nexost = len(self.varvecs['z'])
  719. nendost = len(self.varvecs['k'])
  720. nendocon = len(self.varvecs['y'])
  721. list_tmp1 = COP.deepcopy(self.interm4)
  722. eq_len = len(self.interm4)
  723. sub_list2 = self.vlist2
  724. sub_list = self.vlist
  725. reva2 = self.re_var2
  726. i1=0
  727. for x in list_tmp1:
  728. str_tmp1 = x[:]
  729. i2=0
  730. for y1,y2 in zip(sub_list,sub_list2):
  731. if i1 < eq_len-nexost:
  732. while reva2.search(str_tmp1) != None:
  733. ma1 = reva2.search(str_tmp1)
  734. indx1 = sub_list.index(ma1.group(0))
  735. str_tmp1 = str_tmp1.replace(ma1.group(0),'exp(x0('+str(indx1+1)+'))')[:]
  736. i2 = i2 + 1
  737. else:
  738. while reva2.search(str_tmp1) != None:
  739. ma2 = reva2.search(str_tmp1)
  740. indx2 = sub_list2.index(ma2.group(0))
  741. str_tmp1 = str_tmp1.replace(ma2.group(0),'exp(x0('+str(indx2+1)+'))')[:]
  742. i2 = i2 + 1
  743. list_tmp1[i1] = str_tmp1
  744. i1=i1+1
  745. self.interm5 = list_tmp1
  746. def mkfunc(self):
  747. rege = RE.compile('\*{2,2}')
  748. inde = ' '*2
  749. eq_len=len(self.interm5)
  750. mfile=open(path_opts['MlabPath']['path']+'/Klein/'+'mfunc.m','w')
  751. mfile.write('function y = mfunc(x0)\n')
  752. mfile.write(inde+'%Parameter Values\n')
  753. for x in self.param.items():
  754. mfile.write(inde+x[0]+'='+str(x[1])+';\n')
  755. mfile.write('\n')
  756. mfile.write(inde+'%Steady State Values\n')
  757. for x in self.sstate_list:
  758. x[0]=rege.sub('^',x[0])
  759. x[1]=rege.sub('^',x[1])
  760. mfile.write(inde+x[0]+'='+str(x[1])+';\n')
  761. mfile.write('\n')
  762. mfile.write(inde+'y=zeros('+str(eq_len)+',1);\n')
  763. mfile.write('\n')
  764. for i1,i2 in zip(range(1,eq_len+1,1),self.interm5):
  765. mfile.write(inde+'y('+str(i1)+')='+i2+';'+'\n')
  766. mfile.close()
  767. def mkgrad(self):
  768. self.mkfunc()
  769. sess1 = self.sess1
  770. sstate = self.sstate
  771. ssdic = sstate[0]
  772. ssdic.update(sstate[1])
  773. ssdic2 = {}
  774. for x in ssdic.keys():
  775. if x[-4:] == '_bar':
  776. ssdic2[x] = ssdic[x]
  777. for x in ssdic2.keys():
  778. ssdic2[x] = np.log(ssdic2[x])
  779. vlist2 = []
  780. for x in self.vlist:
  781. ma = self.re_var2.search(x)
  782. tvar = ma.group('var')
  783. tvar = tvar.upper()
  784. tvar = tvar+'_bar'
  785. vlist2.append(tvar)
  786. invec = []
  787. for x in vlist2:
  788. invec.append(ssdic2[x])
  789. mlabraw.eval(sess1,'clear all;')
  790. mlabraw.eval(sess1,'cd '+path_opts['MlabPath']['path'])
  791. mlabraw.eval(sess1,'cd Klein')
  792. mlabraw.put(sess1,'x0',invec)
  793. mlabraw.eval(sess1,"grdm=centgrad('mfunc',x0)")
  794. gradm = np.matrix(mlabraw.get(sess1,'grdm'))
  795. self.gradm = gradm
  796. def mkAB(self):
  797. nexost = len(self.varvecs['z'])
  798. nendost = len(self.varvecs['k'])
  799. nendocon = len(self.varvecs['y'])
  800. A = self.gradm[:,:nexost+nendost+nendocon]
  801. B = -self.gradm[:,nexost+nendost+nendocon:]
  802. self.AA = A
  803. self.BB = B
  804. def solab(self):
  805. A = self.AA
  806. B = self.BB
  807. tstates = len(self.varvecs['k'])+len(self.varvecs['z'])
  808. (F,P,retcon) = isolab(A,B,tstates,MAT.shape(A)[0])
  809. if MAT.sum(P.reshape(-1,1)) == 0.0:
  810. return
  811. else:
  812. self.P = np.matrix(P)
  813. self.F = np.matrix(F)
  814. def mkhess(self):
  815. self.mkfunc()
  816. sess1 = self.sess1
  817. sstate = self.sstate
  818. ssdic = sstate[0]
  819. ssdic.update(sstate[1])
  820. ssdic2 = {}
  821. for x in ssdic.keys():
  822. if x[-4:] == '_bar':
  823. ssdic2[x] = ssdic[x]
  824. for x in ssdic2.keys():
  825. ssdic2[x] = np.log(ssdic2[x])
  826. vlist2 = []
  827. for x in self.vlist:
  828. ma = self.re_var2.search(x)
  829. tvar = ma.group('var')
  830. tvar = tvar.upper()
  831. tvar = tvar+'_bar'
  832. vlist2.append(tvar)
  833. invec = []
  834. for x in vlist2:
  835. invec.append(ssdic2[x])
  836. mlabraw.eval(sess1,'clear all;')
  837. mlabraw.eval(sess1,'cd '+path_opts['MlabPath']['path'])
  838. mlabraw.eval(sess1,'cd Klein')
  839. mlabraw.put(sess1,'x0',invec)
  840. mlabraw.eval(sess1,"hessm=centhess('mfunc',x0)")
  841. hessm = np.matrix(mlabraw.get(sess1,'hessm'))
  842. self.hessm = hessm
  843. def solab2(self):
  844. sess1 = self.sess1
  845. mlabraw.eval(sess1,'clear all;')
  846. mlabraw.eval(sess1,'cd '+path_opts['MlabPath']['path'])
  847. mlabraw.eval(sess1,'cd Klein')
  848. mlabraw.put(sess1,'gradm',self.gradm)
  849. mlabraw.put(sess1,'hessm',self.hessm)
  850. #----------------------------------------------------------------------------------------------------------------------
  851. class MatWood:
  852. def __init__(self,intup):
  853. self.jAA = intup[0]
  854. self.jBB = intup[1]
  855. self.nexo = intup[2]
  856. self.ncon = intup[3]
  857. self.nendo = intup[4]
  858. self.sess1 = intup[5]
  859. self.NY = self.ncon+self.nendo
  860. self.NK = self.nendo
  861. self.NX = self.nexo
  862. self.mkwoodm()
  863. def solve(self):
  864. self.reds()
  865. self.solds()
  866. def mkwoodm(self):
  867. AA = self.jAA
  868. BB = self.jBB
  869. nendo = self.nendo
  870. nexo = self.nexo
  871. ncon = self.ncon
  872. nstates = nexo+nendo
  873. wAA = MAT.hstack((AA[:-nexo,nstates:],AA[:-nexo,nexo:nstates]))
  874. #wAA = MAT.hstack((AA[:,nstates:],AA[:,:nstates]))
  875. wBB = MAT.hstack((BB[:-nexo,nstates:],BB[:-nexo,nexo:nstates]))
  876. #wBB = MAT.hstack((BB[:,nstates:],BB[:,:nstates]))
  877. wCC = BB[:-nexo,:nexo]
  878. #wCC = MAT.zeros((ncon+nstates,1))
  879. self.wAA = wAA
  880. self.wBB = wBB
  881. self.wCC = wCC
  882. def reds(self):
  883. A = self.wAA
  884. B = self.wBB
  885. C = self.wCC
  886. NX = self.NX
  887. NK = self.NK
  888. NY = self.NY
  889. sess1 = self.sess1
  890. mlabraw.eval(sess1,'clear all;')
  891. mlabraw.eval(sess1,'cd '+mlabpath)
  892. mlabraw.eval(sess1,'cd Woodford')
  893. mlabraw.put(sess1,'wAA',A)
  894. mlabraw.put(sess1,'wBB',B)
  895. mlabraw.put(sess1,'wCC',C)
  896. mlabraw.put(sess1,'NX',NX)
  897. mlabraw.put(sess1,'NY',NY)
  898. mlabraw.put(sess1,'NK',NK)
  899. mlabraw.eval(sess1,'[Br,Cr,Lr,NF] = redsf(wAA,wBB,wCC,NY,NX,NK)')
  900. self.Br = np.matrix(mlabraw.get(sess1,'Br'))
  901. self.Cr = np.matrix(mlabraw.get(sess1,'Cr'))
  902. self.Lr = np.matrix(mlabraw.get(sess1,'Lr'))
  903. self.NF = np.matrix(mlabraw.get(sess1,'NF'))
  904. def solds(self):
  905. Br = self.Br
  906. Cr = self.Cr
  907. Lr = self.Lr
  908. NF = self.NF
  909. NX = self.NX
  910. NK = self.NK
  911. NY = self.NY
  912. sess1 = self.sess1
  913. mlabraw.eval(sess1,'clear all;')
  914. mlabraw.eval(sess1,'cd '+mlabpath)
  915. mlabraw.eval(sess1,'cd Woodford')
  916. mlabraw.put(sess1,'Br',Br)
  917. mlabraw.put(sess1,'Cr',Cr)
  918. mlabraw.put(sess1,'Lr',Lr)
  919. mlabraw.put(sess1,'NF',NF)
  920. mlabraw.put(sess1,'NX',NX)
  921. mlabraw.put(sess1,'NY',NY)
  922. mlabraw.put(sess1,'NK',NK)
  923. mlabraw.eval(sess1,'[D,F,G,H] = soldsf(Br,Cr,Lr,NY,NX,NK,NF)')
  924. self.D = np.matrix(mlabraw.get(sess1,'D'))
  925. self.F = np.matrix(mlabraw.get(sess1,'F'))
  926. self.G = np.matrix(mlabraw.get(sess1,'G'))
  927. self.H = np.matrix(mlabraw.get(sess1,'H'))
  928. #----------------------------------------------------------------------------------------------------------------------
  929. class ForKlein:
  930. def __init__(self,intup):
  931. self.uhlig = PyUhlig(intup)
  932. self.uhlig.mkmats()
  933. self.AA = self.uhlig.AA
  934. self.BB = self.uhlig.BB
  935. self.CC = self.uhlig.CC
  936. self.DD = self.uhlig.DD
  937. self.FF = self.uhlig.FF
  938. self.GG = self.uhlig.GG
  939. self.HH = self.uhlig.HH
  940. self.JJ = self.uhlig.JJ
  941. self.KK = self.uhlig.KK
  942. self.LL = self.uhlig.LL
  943. self.MM = self.uhlig.MM
  944. self.NN = self.uhlig.NN
  945. self.mkKleinMats()
  946. self.outdic = {}
  947. def mkKleinMats(self):
  948. # Make uhlig matrices locally available for computations
  949. AA = self.AA
  950. BB = self.BB
  951. CC = self.CC
  952. DD = self.DD
  953. FF = self.FF
  954. GG = self.GG
  955. HH = self.HH
  956. JJ = self.JJ
  957. KK = self.KK
  958. LL = self.LL
  959. MM = self.MM
  960. NN = self.NN
  961. # Determine size of states, endogenous
  962. exo_st = MAT.shape(NN)[1]
  963. endo_st = MAT.shape(BB)[1]
  964. endo_cn = MAT.shape(CC)[1]
  965. n_deteq = MAT.shape(AA)[0]
  966. n_expeq = MAT.shape(JJ)[0]
  967. tot_st = exo_st+endo_st
  968. self.tstates = tot_st
  969. tot_var = tot_st+endo_cn
  970. klein_A_rtwo = MAT.hstack((LL,GG))
  971. klein_A_rtwo = MAT.hstack((klein_A_rtwo,JJ))
  972. klein_A_rtwo_rows = MAT.shape(klein_A_rtwo)[0]
  973. klein_A_rtwo_cols = MAT.shape(klein_A_rtwo)[1]
  974. klein_A_rone = MAT.zeros((exo_st,klein_A_rtwo_cols))
  975. klein_A_rone = MAT.hstack((MAT.identity(exo_st),klein_A_rone[:,exo_st:]))
  976. klein_A_rthree = MAT.hstack((MAT.zeros((n_deteq,exo_st)),AA))
  977. klein_A_rthree = MAT.hstack((klein_A_rthree,MAT.zeros((n_deteq,endo_cn))))
  978. klein_A = MAT.vstack((klein_A_rone,klein_A_rtwo))
  979. klein_A = MAT.vstack((klein_A,klein_A_rthree))
  980. klein_B_rone = MAT.zeros((exo_st,klein_A_rtwo_cols))
  981. klein_B_rone = MAT.hstack((NN,klein_B_rone[:,exo_st:]))
  982. klein_B_rtwo = MAT.hstack((-MM,-HH))
  983. klein_B_rtwo = MAT.hstack((klein_B_rtwo,-KK))
  984. klein_B_rthree = MAT.hstack((-DD,-BB))
  985. klein_B_rthree = MAT.hstack((klein_B_rthree,-CC))
  986. klein_B = MAT.vstack((klein_B_rone,klein_B_rtwo))
  987. klein_B = MAT.vstack((klein_B,klein_B_rthree))
  988. self.A = klein_A
  989. self.B = klein_B
  990. def solve(self):
  991. A = self.A
  992. B = self.B
  993. tstates = MAT.shape(self.AA)[1] + MAT.shape(self.DD)[1]
  994. (F,P,retcon) = isolab(A,B,tstates,MAT.shape(A)[0])
  995. if MAT.sum(P.reshape(-1,1)) == 0.0:
  996. return
  997. else:
  998. self.P = np.matrix(P)
  999. self.F = np.matrix(F)
  1000. #----------------------------------------------------------------------------------------------------------------------
  1001. class PyKlein2D(object):
  1002. def __init__(self,intup,other=None):
  1003. if other != None:
  1004. self.other = other
  1005. self.gra = intup[0]
  1006. self.hes = intup[1]
  1007. self.nendo = intup[2]
  1008. self.nexo = intup[3]
  1009. self.ncon = intup[4]
  1010. self.sigma = intup[5]
  1011. self.A = intup[6]
  1012. self.B = intup[7]
  1013. self.vardic = intup[8]
  1014. self.vdic = intup[9]
  1015. self.modname = intup[10]
  1016. self.audic = intup[11]
  1017. self.nacon = len(self.audic['con']['var'])
  1018. self.naendo = len(self.audic['endo']['var'])
  1019. if self.vardic['other']['var']:
  1020. self.numjl = intup[12]
  1021. self.numhl = intup[13]
  1022. self.nother = intup[14]
  1023. self.oswitch = 1
  1024. kintup = (self.gra,self.nendo,
  1025. self.nexo,self.ncon,
  1026. self.sigma,self.A,self.B,
  1027. self.vardic,self.vdic,
  1028. self.modname,self.audic,
  1029. self.numjl,self.nother)
  1030. else:
  1031. self.oswitch = 0
  1032. kintup = (self.gra,self.nendo,
  1033. self.nexo,self.ncon,
  1034. self.sigma,self.A,self.B,
  1035. self.vardic,self.vdic,
  1036. self.modname,self.audic)
  1037. self.tstates = self.nendo+self.nexo
  1038. self.forkleind = ForKleinD(kintup)
  1039. self.ssigma = self.mkssigma(self.tstates,self.nexo,self.sigma)
  1040. def mkssigma(self,tstates,nexo,sigma):
  1041. ssigma = MAT.zeros((tstates,tstates))
  1042. for i in range(nexo):
  1043. ssigma[i,i] = sigma[i,i]
  1044. return ssigma
  1045. def solab2(self):
  1046. # Tracem function
  1047. def tracem(xmat):
  1048. n = MAT.shape(xmat)[1]
  1049. m = MAT.shape(xmat)[0]/n
  1050. ymat = MAT.zeros((m,1))
  1051. for i1 in xrange(int(m)):
  1052. ymat[i1,0]=MAT.trace(xmat[n*i1:i1*n+1,:n])
  1053. return ymat
  1054. ssigma = self.ssigma
  1055. pp = self.P
  1056. ff = self.F
  1057. gra = self.gra
  1058. hes = self.hes
  1059. m = self.ncon+self.nendo+self.nexo
  1060. ny = self.ncon
  1061. nx = self.tstates
  1062. f1 = gra[:,:nx]
  1063. f2 = gra[:,nx:m]
  1064. f4 = gra[:,m+nx:2*m]
  1065. mm = MAT.vstack((pp,ff*pp,MAT.eye(nx),ff))
  1066. aa1 = MAT.kron(MAT.eye(m),mm.T)*hes*mm
  1067. bb1 = MAT.kron(f1,MAT.eye(nx))
  1068. bb2 = MAT.kron(f2,MAT.eye(nx))
  1069. bb4 = MAT.kron(f4,MAT.eye(nx))
  1070. cc1 = MAT.kron(MAT.eye(ny),pp.T)
  1071. cc2 = MAT.kron(ff,MAT.eye(nx))
  1072. aa_1 = MAT.kron(MAT.eye(nx),bb4)+MAT.kron(pp.T,bb2*cc1)
  1073. aa_2 = MAT.kron(MAT.eye(nx),bb1+bb2*cc2)
  1074. aa = MAT.hstack((aa_1,aa_2))
  1075. sol = np.linalg.solve(-aa,HLP.ctr(aa1.flatten(1)))
  1076. ee = HLP.ctr(sol[:nx**2*ny].reshape(-1,nx*ny))
  1077. gg = HLP.ctr(sol[nx**2*ny:].reshape(-1,nx**2))
  1078. ma = 2.0*MAT.hstack((f1+f2*ff,f2+f4))
  1079. eyeff = MAT.vstack((MAT.eye(nx),ff,MAT.zeros((m,nx))))
  1080. ve_1 = f2*tracem(MAT.kron(MAT.eye(ny),ssigma)*ee)
  1081. ve_2 = tracem(MAT.kron(MAT.eye(m),HLP.ctr(eyeff))*hes*eyeff*ssigma)
  1082. ve = ve_1 + ve_2
  1083. kxy = -(ma.I)*ve
  1084. kx = kxy[:nx]
  1085. ky = kxy[nx:]
  1086. self.E = ee
  1087. self.G = gg
  1088. self.KX = kx
  1089. self.KY = ky
  1090. def solve(self):
  1091. self.forkleind.solve()
  1092. self.P = self.forkleind.P
  1093. self.F = self.forkleind.F
  1094. self.solab2()
  1095. def sim(self,tlen,sntup=None):
  1096. # Deals with 0-tuples
  1097. if type(sntup) != type((1,2,3)) and type(sntup) == type('abc'):
  1098. sntup = (sntup,)
  1099. # Add 1000 observations, as they will be thrown away
  1100. # Add one more observation to start first-order vector
  1101. exoli = [x[1] for x in self.vardic['exo']['var']]
  1102. indx=[]
  1103. if sntup == None:
  1104. indx = range(len(exoli))
  1105. else:
  1106. for name in sntup:
  1107. if name not in exoli:
  1108. return 'Error: '+name+' is not a valid exo variable for this model!'
  1109. else:
  1110. indx.append(exoli.index(name))
  1111. indx.sort()
  1112. ncon = self.ncon
  1113. nexo = self.nexo
  1114. nendo = self.nendo
  1115. tstates = self.tstates
  1116. tlena = 1000+tlen
  1117. sigma = self.sigma
  1118. ssigma = self.ssigma
  1119. if self.oswitch:
  1120. numjl = self.numjl
  1121. numhl = self.numhl
  1122. kx = self.KX
  1123. ky = self.KY
  1124. pp = self.P
  1125. ff = self.F
  1126. ee = self.E
  1127. gg = self.G
  1128. count = 0
  1129. for varia in MAT.diag(sigma):
  1130. if locals().has_key('ranvec'):
  1131. if count in indx:
  1132. ranvec = MAT.vstack((ranvec,N.sqrt(varia)*MAT.matrix(N.random.standard_normal(tlena))))
  1133. else:
  1134. ranvec = MAT.vstack((ranvec,MAT.zeros((1,tlena))))
  1135. else:
  1136. if count in indx:
  1137. ranvec = np.sqrt(varia)*MAT.matrix(N.random.standard_normal(tlena))
  1138. else:
  1139. ranvec = MAT.zeros((1,tlena))
  1140. count = count + 1
  1141. ranvec = MAT.vstack((ranvec,MAT.zeros((nendo,tlena))))
  1142. x_one_m1 = ranvec[:,0]
  1143. x_one_0 = pp*x_one_m1
  1144. x_two_m1 = kx + ranvec[:,0]
  1145. y_one_0 = ff*x_one_m1
  1146. y_one_m1 = MAT.zeros(y_one_0.shape)
  1147. y_two_0 = ky+0.5*MAT.kron(MAT.eye(ncon),x_one_m1.T)*ee*x_one_m1
  1148. if self.oswitch:
  1149. nother = self.nother
  1150. o_one_0 = numjl*MAT.vstack((x_one_0,y_one_0,x_one_m1,y_one_m1))
  1151. o_two_0 = numjl*MAT.vstack((x_one_0,y_one_0,x_one_m1,y_one_m1))+\
  1152. 0.5*MAT.kron(MAT.eye(nother),MAT.vstack((x_one_0,y_one_0,x_one_m1,y_one_m1)).T)*\
  1153. numhl*MAT.vstack((x_one_0,y_one_0,x_one_m1,y_one_m1))
  1154. x_one_c = COP.deepcopy(x_one_m1)
  1155. y_one_c = COP.deepcopy(y_one_0)
  1156. x_two_c = COP.deepcopy(x_two_m1)
  1157. y_two_c = COP.deepcopy(y_two_0)
  1158. if self.oswitch:
  1159. o_one_c = COP.deepcopy(o_one_0)
  1160. o_two_c = COP.deepcopy(o_two_0)
  1161. x_one = COP.deepcopy(x_one_c)
  1162. y_one = COP.deepcopy(y_one_c)
  1163. x_two = COP.deepcopy(x_two_c)
  1164. y_two = COP.deepcopy(y_two_c)
  1165. if self.oswitch:
  1166. o_one = COP.deepcopy(o_one_c)
  1167. o_two = COP.deepcopy(o_two_c)
  1168. for i1 in range(1,ranvec.shape[1],1):
  1169. x_one_n = pp*x_one_c+ranvec[:,i1]
  1170. y_one_n = ff*x_one_c
  1171. x_two_n = kx+pp*x_two_c+\
  1172. 0.5*MAT.kron(MAT.eye(tstates),x_one_c.T)*\
  1173. gg*x_one_c+ranvec[:,i1]
  1174. y_two_n = ky+ff*x_two_c+\
  1175. 0.5*MAT.kron(MAT.eye(ncon),x_one_c.T)*\
  1176. ee*x_one_c
  1177. if self.oswitch:
  1178. o_one_n = numjl*MAT.vstack((x_one_n,y_one_n,x_one_c,y_one_c))
  1179. o_two_n = numjl*MAT.vstack((x_one_n,y_one_n,x_one_c,y_one_c))+\
  1180. 0.5*MAT.kron(MAT.eye(nother),MAT.vstack((x_one_n,y_one_n,x_one_c,y_one_c)).T)*\
  1181. numhl*MAT.vstack((x_one_n,y_one_n,x_one_c,y_one_c))
  1182. x_one = MAT.hstack((x_one,x_one_c))
  1183. y_one = MAT.hstack((y_one,y_one_n))
  1184. x_two = MAT.hstack((x_two,x_two_c))
  1185. y_two = MAT.hstack((y_two,y_two_n))
  1186. if self.oswitch:
  1187. o_one = MAT.hstack((o_one,o_one_n))
  1188. o_two = MAT.hstack((o_two,o_two_n))
  1189. x_one_c = x_one_n
  1190. y_one_c = y_one_n
  1191. x_two_c = x_one_n
  1192. y_two_c = y_two_n
  1193. if self.oswitch:
  1194. o_one_c = o_one_n
  1195. o_two_c = o_two_n
  1196. # Throw away first 1000 obs
  1197. x_one = x_one[:,1000:]
  1198. y_one = y_one[:,1000:]
  1199. y_two = y_two[:,1000:]
  1200. x_two = x_two[:,1000:]
  1201. if self.oswitch:
  1202. o_one = o_one[:,1000:]
  1203. o_two = o_two[:,1000:]
  1204. self.sim_y_two = y_two
  1205. self.sim_y_one = y_one
  1206. self.sim_x_two = x_two
  1207. self.sim_x_one = x_one
  1208. self.insim = [self.sim_x_two,self.sim_y_two]
  1209. if self.oswitch:
  1210. self.sim_o_one = o_one
  1211. self.sim_o_two = o_two
  1212. self.insim = self.insim + [self.sim_o_two,]
  1213. def mkcvar(self,vname=False,insim='insim'):
  1214. # Now also produce unconditional variances, and normal. variances with v
  1215. # Check if simul data is available
  1216. if insim not in dir(self):
  1217. return "Error: Can't produce uncond. variance table without simulation data!"
  1218. exoli = [x[1] for x in self.vardic['exo']['var']]
  1219. endoli = [x[1] for x in self.vardic['endo']['var']]
  1220. stateli = exoli + endoli
  1221. conli = [x[1] for x in self.vardic['con']['var']]
  1222. alli = stateli+conli
  1223. if self.oswitch:
  1224. otherli = [x[1] for x in self.vardic['other']['var']]
  1225. alli = alli + otherli
  1226. # Check if vname is valid
  1227. if vname not in alli:
  1228. return 'Error: '+vname+' is not a valid variable for this model!'
  1229. insim = eval('self.'+insim)
  1230. osim_x = COP.deepcopy(insim[0])
  1231. osim_y = COP.deepcopy(insim[1])
  1232. nendo = self.nendo
  1233. nexo = self.nexo
  1234. ncon = self.ncon
  1235. # Now hp filter the simulations before graphing according to filtup
  1236. for i1 in xrange(osim_y.shape[0]):
  1237. yy = osim_y[i1,:].__array__().T
  1238. woy = np.zeros((osim_y.shape[1],3))
  1239. lam = 1600
  1240. yyf = MAT.matrix(hpfilter(data=yy,lam=1600))
  1241. osim_y[i1,:] = yyf[0]
  1242. # Now filter the state variables!
  1243. for i1 in xrange(osim_x.shape[0]):
  1244. xx = osim_x[i1,:].__array__().T
  1245. wox = np.zeros((osim_x.shape[1],3))
  1246. lam = 1600
  1247. xxf = MAT.matrix(hpfilter(data=xx,lam=1600))
  1248. osim_x[i1,:] = xxf[0]
  1249. if self.oswitch:
  1250. osim_o = COP.deepcopy(insim[2])
  1251. # Now hp filter the other variables!
  1252. for i1 in xrange(osim_o.shape[0]):
  1253. oo = osim_o[i1,:].__array__().T
  1254. woo = np.zeros((osim_o.shape[1],3))
  1255. lam = 1600
  1256. oof = MAT.matrix(hpfilter(data=oo,lam=1600))
  1257. osim_o[i1,:] = oof[0]
  1258. # Stack all matrices into one
  1259. allmat = MAT.vstack((osim_x,osim_y))
  1260. if self.oswitch:
  1261. allmat = MAT.vstack((allmat,osim_o))
  1262. varmat = MAT.zeros((allmat.shape[0],1))
  1263. for i1 in range(allmat.shape[0]):
  1264. varmat[i1,0] = np.var(allmat[i1,:].A.flatten(1))
  1265. if vname:
  1266. relmat = MAT.zeros((allmat.shape[0],1))
  1267. indx = alli.index(vname)
  1268. varvari = np.var(allmat[indx,:].A.flatten(1))
  1269. for i1 in range(allmat.shape[0]):
  1270. relmat[i1,0] = varmat[i1,0]/varvari
  1271. self.cvarm = MAT.hstack((varmat,relmat))
  1272. else:
  1273. self.cvarm = varmat
  1274. def mkact(self,vname,intup=None,insim='insim'):
  1275. # Now also produce autocorrelation table
  1276. # Check if simul data is available
  1277. if insim not in dir(self):
  1278. return "Error: Can't produce autocorrelation table without simulation data!"
  1279. exoli = [x[1] for x in self.vardic['exo']['var']]
  1280. endoli = [x[1] for x in self.vardic['endo']['var']]
  1281. stateli = exoli + endoli
  1282. conli = [x[1] for x in self.vardic['con']['var']]
  1283. alli = stateli+conli
  1284. if self.oswitch:
  1285. otherli = [x[1] for x in self.vardic['other']['var']]
  1286. alli = alli + otherli
  1287. # Check if vname is valid
  1288. if vname not in alli:
  1289. return 'Error: '+vname+' is not a valid variable for this model!'
  1290. if intup == None:
  1291. lags = 3
  1292. leads = 3
  1293. else:
  1294. lags = intup[0]
  1295. leads = intup[1]
  1296. insim = eval('self.'+insim)
  1297. osim_x = COP.deepcopy(insim[0])
  1298. osim_y = COP.deepcopy(insim[1])
  1299. # Now hp filter the simulations before graphing according to filtup
  1300. for i1 in xrange(osim_y.shape[0]):
  1301. yy = osim_y[i1,:].__array__().T
  1302. woy = np.zeros((osim_y.shape[1],3))
  1303. lam = 1600
  1304. yyf = MAT.matrix(hpfilter(data=yy,lam=1600))
  1305. osim_y[i1,:] = yyf[0]
  1306. # Now filter the state variables!
  1307. for i1 in xrange(osim_x.shape[0]):
  1308. xx = osim_x[i1,:].__array__().T
  1309. wox = np.zeros((osim_x.shape[1],3))
  1310. lam = 1600
  1311. xxf = MAT.matrix(hpfilter(data=xx,lam=1600))
  1312. osim_x[i1,:] = xxf[0]
  1313. sim_x = osim_x[:,lags:-leads]
  1314. sim_xf = osim_x[:,leads+1:]
  1315. sim_yf = osim_y[:,leads+1:]
  1316. sim_y = osim_y[:,lags:-leads]
  1317. sim_xl = osim_x[:,:-lags-1]
  1318. sim_yl = osim_y[:,:-lags-1]
  1319. if self.oswitch:
  1320. osim_o = COP.deepcopy(insim[2])
  1321. # Now hp filter the other variables!
  1322. for i1 in xrange(osim_o.shape[0]):
  1323. oo = osim_o[i1,:].__array__().T
  1324. woo = np.zeros((osim_o.shape[1],3))
  1325. lam = 1600
  1326. oof = MAT.matrix(hpfilter(data=oo,lam=1600))
  1327. osim_o[i1,:] = oof[0]
  1328. sim_o = osim_o[:,lags:-leads]
  1329. sim_of = osim_o[:,leads+1:]
  1330. sim_ol = osim_o[:,:-lags-1]
  1331. alli = alli + otherli
  1332. posa = alli.index(vname)
  1333. actm = MAT.zeros((len(alli),lags+1+leads))
  1334. sima = MAT.vstack((sim_x,sim_y))
  1335. sima_f = MAT.vstack((sim_xf,sim_yf))
  1336. sima_l = MAT.vstack((sim_xl,sim_yl))
  1337. if self.oswitch:
  1338. sima = MAT.vstack((sima,sim_o))
  1339. sima_f = MAT.vstack((sima_f,sim_of))
  1340. sima_l = MAT.vstack((sima_l,sim_ol))
  1341. for i1 in range(sima.shape[0]):
  1342. # Do lags
  1343. for i2 in range(lags):
  1344. actm[i1,i2] = np.round(np.corrcoef(sima[posa,:].A.flatten(1),sima_l[i1,i2:sima_l.shape[1]-lags+i2+1].A.flatten(1))[1,0],3)
  1345. # Do current
  1346. actm[i1,lags] = np.round(np.corrcoef(sima[posa,:].A.flatten(1),sima[i1,:].A.flatten(1))[1,0],3)
  1347. # Do leads
  1348. for i2 in range(leads):
  1349. actm[i1,lags+1+i2] = np.round(np.corrcoef(sima[posa,:].A.flatten(1),sima_f[i1,i2:sima_f.shape[1]-leads+i2+1].A.flatten(1))[1,0],3)
  1350. self.actm = actm
  1351. self.actname = vname
  1352. if intup:
  1353. self.actin = intup
  1354. def show_act(self):
  1355. if 'actname' not in dir(self):
  1356. return 'Error: You have not produced any autocorrelation table yet!'
  1357. nexo = self.nexo
  1358. nendo = self.nendo
  1359. ncon = self.ncon
  1360. if 'naendo' in dir(self):
  1361. naendo = self.naendo
  1362. else:
  1363. naendo = 0
  1364. if 'nacon' in dir(self):
  1365. nacon = self.nacon
  1366. else:
  1367. nacon = 0
  1368. nother = len(self.vardic['other']['var'])
  1369. respva = COP.deepcopy(self.actname)
  1370. if 'actin' in dir(self):
  1371. lags = COP.deepcopy(int(self.actin[0]))
  1372. leads = COP.deepcopy(int(self.actin[1]))
  1373. else:
  1374. lags = 3
  1375. leads = 3
  1376. actm = COP.deepcopy(self.actm)
  1377. vdic = self.vdic
  1378. allvari = [x[1] for x in vdic['exo']]
  1379. allvari = allvari + [x[1] for x in vdic['endo']]
  1380. allvari = allvari + [x[1] for x in vdic['con']]
  1381. if self.oswitch:
  1382. allvari = allvari + [x[1] for x in vdic['other']]
  1383. allvari = allvari[:nexo+nendo-naendo]+allvari[nexo+nendo:nexo+nendo+ncon-nacon]
  1384. actm = MAT.vstack((actm[:nexo+nendo-naendo,:],actm[nexo+nendo:nexo+nendo+ncon-nacon,:]))
  1385. # determine longest varname
  1386. vnmax = 0
  1387. for vari in allvari:
  1388. if len(vari) > vnmax:
  1389. vnmax = len(vari)
  1390. print ''
  1391. print 'Autocorrelation table, current '+respva
  1392. print '='*65
  1393. for i1,vari in enumerate(allvari):
  1394. print vari+(vnmax-len(vari))*' '+' |'+str(actm[i1,:])[2:-2]
  1395. def show_sim(self,intup,filtup=None,insim='insim'):
  1396. # Deals with 0-tuples
  1397. if type(intup) != type((1,2,3)) and type(intup) == type('abc'):
  1398. intup = (intup,)
  1399. # Check if simulations have been carried out
  1400. if insim not in dir(self):
  1401. return 'Error: You have not produced any simulations yet! Nothing to graph!'
  1402. mname = self.modname
  1403. vardic = self.vardic
  1404. insim = eval('self.'+insim)
  1405. sim_x = COP.deepcopy(insim[0])
  1406. sim_y = COP.deepcopy(insim[1])
  1407. tlen = sim_x.shape[1]
  1408. if self.oswitch:
  1409. sim_o = COP.deepcopy(insim[2])
  1410. nother = self.nother
  1411. otherli = [x[1] for x in vardic['other']['var']]
  1412. nexo = self.nexo
  1413. nendo = self.nendo
  1414. ncon = self.ncon
  1415. conli = [x[1] for x in vardic['con']['var']]
  1416. endoli = [x[1] for x in vardic['endo']['var']]
  1417. exoli = [x[1] for x in vardic['exo']['var']]
  1418. # If filtup is None, create filtup from vardic
  1419. if filtup == None:
  1420. filli = [0]*len(intup)
  1421. for i1,x in enumerate(intup):
  1422. for y in vardic.keys():
  1423. if x in [z[1] for z in vardic[y]['var']]:
  1424. indx = [z[1] for z in vardic[y]['var']].index(x)
  1425. if 'hp' in [z for z in vardic[y]['mod']][indx]:
  1426. filli[i1] = 1
  1427. elif 'bk' in [z for z in vardic[y]['mod']][indx]:
  1428. filli[i1] = 2
  1429. elif 'cf' in [z for z in vardic[y]['mod']][indx]:
  1430. filli[i1] = 3
  1431. filtup = tuple(filli)
  1432. stateli = exoli+endoli
  1433. alli = stateli+conli
  1434. if self.oswitch:
  1435. alli = alli+otherli
  1436. # Check if all name in intup are available to graph
  1437. for name in intup:
  1438. if name not in alli:
  1439. return 'Error: '+name+' is not a valid variable name for this model!'
  1440. # Create x, y and z indeces
  1441. indx = []
  1442. indy = []
  1443. indo = []
  1444. for name in intup:
  1445. if name in stateli:
  1446. indx.append(stateli.index(name))
  1447. elif name in conli:
  1448. indy.append(conli.index(name))
  1449. elif self.oswitch and name in otherli:
  1450. indo.append(otherli.index(name))
  1451. leg = []
  1452. indx.sort()
  1453. indy.sort()
  1454. indo.sort()
  1455. # Now hp filter the simulations before graphing according to filtup
  1456. for i1 in xrange(sim_y.shape[0]):
  1457. if indy and (i1 in indy) and filtup[list(intup).index(conli[i1])]:
  1458. if filtup[list(intup).index(conli[i1])] == 1:
  1459. conli[i1] = conli[i1]+'(hpf)'
  1460. yy = sim_y[i1,:].__array__().T
  1461. woy = np.zeros((tlen,3))
  1462. lam = 1600
  1463. yyf = MAT.matrix(hpfilter(data=yy,lam=1600))
  1464. sim_y[i1,:] = yyf[0]*100.0
  1465. elif filtup[list(intup).index(conli[i1])] == 2:
  1466. conli[i1] = conli[i1]+'(bkf)'
  1467. yy = sim_y[i1,:].__array__().T
  1468. woy = np.zeros((tlen,1))
  1469. up = 6
  1470. dn = 32
  1471. kkl = 12
  1472. yyf = MAT.matrix(bkfilter(data=yy,up=up,dn=dn,kkl=kkl))
  1473. sim_y[i1,:] = yyf[0]*100.0
  1474. elif filtup[list(intup).index(conli[i1])] == 3:
  1475. conli[i1] = conli[i1]+'(cff)'
  1476. yy = sim_y[i1,:].__array__().T
  1477. woy = np.zeros((tlen,1))
  1478. low = 6
  1479. high = 32
  1480. drift = True
  1481. yyf = MAT.matrix(cffilter(data=yy,low=low,high=high,drift=drift))
  1482. sim_y[i1,:] = yyf[0]*100.0
  1483. # Now filter the state variables!
  1484. for i1 in xrange(sim_x.shape[0]):
  1485. if indx and (i1 in indx) and filtup[list(intup).index(stateli[i1])]:
  1486. if filtup[list(intup).index(stateli[i1])] == 1:
  1487. stateli[i1] = stateli[i1]+'(hpf)'
  1488. xx = sim_x[i1,:].__array__().T
  1489. wox = np.zeros((tlen,3))
  1490. lam = 1600
  1491. xxf = MAT.matrix(hpfilter(data=xx,lam=1600))
  1492. sim_x[i1,:] = xxf[0]*100.0
  1493. elif filtup[list(intup).index(stateli[i1])] == 2:
  1494. stateli[i1] = stateli[i1]+'(bkf)'
  1495. xx = sim_x[i1,:].__array__().T
  1496. wox = np.zeros((tlen,1))
  1497. up = 6
  1498. dn = 32
  1499. kkl = 12
  1500. xxf = MAT.matrix(bkfilter(data=xx,up=up,dn=dn,kkl=kkl))
  1501. sim_x[i1,:] = xxf[0]*100.0
  1502. elif filtup[list(intup).index(stateli[i1])] == 3:
  1503. stateli[i1] = stateli[i1]+'(cff)'
  1504. xx = sim_x[i1,:].__array__().T
  1505. wox = np.zeros((tlen,1))
  1506. low = 6
  1507. high = 32
  1508. drift = True
  1509. xxf = MAT.matrix(cffilter(data=xx,low=low,high=high,drift=drift))
  1510. sim_x[i1,:] = xxf[0]*100.0
  1511. # Now hp filter the other variables!
  1512. if self.oswitch:
  1513. for i1 in xrange(sim_o.shape[0]):
  1514. if indo and (i1 in indo) and filtup[list(intup).index(otherli[i1])]:
  1515. if filtup[list(intup).index(otherli[i1])] == 1:
  1516. otherli[i1] = otherli[i1]+'(hpf)'
  1517. oo = sim_o[i1,:].__array__().T
  1518. woo = np.zeros((tlen,3))
  1519. lam = 1600
  1520. oof = MAT.matrix(hpfilter(data=oo,lam=1600))
  1521. elif filtup[list(intup).index(otherli[i1])] == 2:
  1522. otherli[i1] = otherli[i1]+'(bkf)'
  1523. oo = sim_o[i1,:].__array__().T
  1524. woo = np.zeros((tlen,1))
  1525. up = 6
  1526. dn = 32
  1527. kkl = 12
  1528. oof = MAT.matrix(bkfilter(data=oo,up=up,dn=dn,kkl=kkl))
  1529. elif filtup[list(intup).index(otherli[i1])] == 3:
  1530. otherli[i1] = otherli[i1]+'(cff)'
  1531. oo = sim_o[i1,:].__array__().T
  1532. woo = np.zeros((tlen,1))
  1533. low = 6
  1534. high = 32
  1535. drift = True
  1536. oof = MAT.matrix(cffilter(data=oo,low=low,high=high,drift=drift))
  1537. if indx and indy and indo:
  1538. for x in indx:
  1539. leg.append(stateli[x])
  1540. for y in indy:
  1541. leg.append(conli[y])
  1542. for o in indo:
  1543. leg.append(otherli[o])
  1544. leg = tuple(leg)
  1545. figo = P.figure()
  1546. P.plot(MAT.hstack((sim_x.T[:,indx],sim_y.T[:,indy],sim_o.T[:,indo])).A)
  1547. P.title(str(tlen)+' simulated periods, '+mname)
  1548. P.xlabel('Time')
  1549. P.ylabel('Percentage deviation from SS')
  1550. P.grid()
  1551. P.legend(leg)
  1552. elif not indx and indy and indo:
  1553. for y in indy:
  1554. leg.append(conli[y])
  1555. for o in indo:
  1556. leg.append(otherli[o])
  1557. leg = tuple(leg)
  1558. figo = P.figure()
  1559. P.plot(MAT.hstack((sim_y.T[:,indy],sim_o.T[:,indo])).A)
  1560. P.title(str(tlen)+' simulated periods, '+mname)
  1561. P.xlabel('Time')
  1562. P.ylabel('Percentage deviation from SS')
  1563. P.grid()
  1564. P.legend(leg)
  1565. elif indx and not indy and indo:
  1566. for x in indx:
  1567. leg.append(stateli[x])
  1568. for o in indo:
  1569. leg.append(otherli[o])
  1570. leg = tuple(leg)
  1571. figo = P.figure()
  1572. P.plot(MAT.hstack((sim_x.T[:,indx],sim_o.T[:,indo])).A)
  1573. P.title(str(tlen)+' simulated periods, '+mname)
  1574. P.xlabel('Time')
  1575. P.ylabel('Percentage deviation from SS')
  1576. P.grid()
  1577. P.legend(leg)
  1578. elif indx and indy and not indo:
  1579. for x in indx:
  1580. leg.append(stateli[x])
  1581. for y in indy:
  1582. leg.append(conli[y])
  1583. leg = tuple(leg)
  1584. figo = P.figure()
  1585. P.plot(MAT.hstack((sim_x.T[:,indx],sim_y.T[:,indy])).A)
  1586. P.title(str(tlen)+' simulated periods, '+mname)
  1587. P.xlabel('Time')
  1588. P.ylabel('Percentage deviation from SS')
  1589. P.grid()
  1590. P.legend(leg)
  1591. elif indx and not indy and not indo:
  1592. for x in indx:
  1593. leg.append(stateli[x])
  1594. leg = tuple(leg)
  1595. figo = P.figure()
  1596. P.plot(sim_x.T[:,indx].A)
  1597. P.title(str(tlen)+' simulated periods, '+mname)
  1598. P.xlabel('Time')
  1599. P.ylabel('Percentage deviation from SS')
  1600. P.grid()
  1601. P.legend(leg)
  1602. elif not indx and indy and not indo:
  1603. for y in indy:
  1604. leg.append(conli[y])
  1605. leg = tuple(leg)
  1606. figo = P.figure()
  1607. P.plot(sim_y.T[:,indy].A)
  1608. P.title(str(tlen)+' simulated periods, '+mname)
  1609. P.xlabel('Time')
  1610. P.ylabel('Percentage deviation from SS')
  1611. P.grid()
  1612. P.legend(leg)
  1613. elif not indx and not indy and indo:
  1614. for o in indo:
  1615. leg.append(otherli[o])
  1616. leg = tuple(leg)
  1617. figo = P.figure()
  1618. P.plot(sim_o.T[:,indo].A)
  1619. P.title(str(tlen)+' simulated periods, '+mname)
  1620. P.xlabel('Time')
  1621. P.ylabel('Percentage deviation from SS')
  1622. P.grid()
  1623. P.legend(leg)
  1624. return figo
  1625. def save_sim(self,intup,fpath=None,filtup=None,insim='insim'):
  1626. # Check if simulations have been carried out
  1627. if insim not in dir(self):
  1628. return 'Error: You have not produced any simulations yet! Nothing to graph!'
  1629. if fpath == None:
  1630. return 'Error: You have not supplied the function with an fpath= argument where to save the plot!'
  1631. mname = self.modname
  1632. vardic = self.vardic
  1633. insim = eval('self.'+insim)
  1634. sim_x = COP.deepcopy(insim[0])
  1635. sim_y = COP.deepcopy(insim[1])
  1636. tlen = sim_x.shape[1]
  1637. if self.oswitch:
  1638. sim_o = COP.deepcopy(insim[2])
  1639. nother = self.nother
  1640. otherli = [x[1] for x in vardic['other']['var']]
  1641. nexo = self.nexo
  1642. nendo = self.nendo
  1643. ncon = self.ncon
  1644. conli = [x[1] for x in vardic['con']['var']]
  1645. endoli = [x[1] for x in vardic['endo']['var']]
  1646. exoli = [x[1] for x in vardic['exo']['var']]
  1647. # If filtup is None, create filtup from vardic
  1648. if filtup == None:
  1649. filli = [0]*len(intup)
  1650. for i1,x in enumerate(intup):
  1651. for y in vardic.keys():
  1652. if x in [z[1] for z in vardic[y]['var']]:
  1653. indx = [z[1] for z in vardic[y]['var']].index(x)
  1654. if 'hp' in [z for z in vardic[y]['mod']][indx]:
  1655. filli[i1] = 1
  1656. elif 'bk' in [z for z in vardic[y]['mod']][indx]:
  1657. filli[i1] = 2
  1658. filtup = tuple(filli)
  1659. stateli = exoli+endoli
  1660. alli = stateli+conli
  1661. if self.oswitch:
  1662. alli = alli+otherli
  1663. # Check if all name in intup are available to graph
  1664. for name in intup:
  1665. if name not in alli:
  1666. return 'Error: '+name+' is not a valid variable name for this model!'
  1667. # Create x, y and z indeces
  1668. indx = []
  1669. indy = []
  1670. indo = []
  1671. for name in intup:
  1672. if name in stateli:
  1673. indx.append(stateli.index(name))
  1674. elif name in conli:
  1675. indy.append(conli.index(name))
  1676. elif self.oswitch and name in otherli:
  1677. indo.append(otherli.index(name))
  1678. leg = []
  1679. indx.sort()
  1680. indy.sort()
  1681. indo.sort()
  1682. # Now hp filter the simulations before graphing according to filtup
  1683. for i1 in xrange(sim_y.shape[0]):
  1684. if indy and (i1 in indy) and filtup[list(intup).index(conli[i1])]:
  1685. if filtup[list(intup).index(conli[i1])] == 1:
  1686. conli[i1] = conli[i1]+'(hpf)'
  1687. yy = sim_y[i1,:].__array__().T
  1688. woy = np.zeros((tlen,3))
  1689. lam = 1600
  1690. yyf = MAT.matrix(hpfilter(data=yy,lam=1600))
  1691. sim_y[i1,:] = yyf[0]*100
  1692. elif filtup[list(intup).index(conli[i1])] == 2:
  1693. conli[i1] = conli[i1]+'(bkf)'
  1694. yy = sim_y[i1,:].__array__().T
  1695. woy = np.zeros((tlen,1))
  1696. up = 6
  1697. dn = 32
  1698. kkl = 12
  1699. yyf = MAT.matrix(bkfilter(yy,up,dn,kkl,tlen))
  1700. sim_y[i1,:] = yyf[0]*100
  1701. # Now filter the state variables!
  1702. for i1 in xrange(sim_x.shape[0]):
  1703. if indx and (i1 in indx) and filtup[list(intup).index(stateli[i1])]:
  1704. if filtup[list(intup).index(stateli[i1])] == 1:
  1705. stateli[i1] = stateli[i1]+'(hpf)'
  1706. xx = sim_x[i1,:].__array__().T
  1707. wox = np.zeros((tlen,3))
  1708. lam = 1600
  1709. xxf = MAT.matrix(hpfilter(data=xx,lam=1600))
  1710. sim_x[i1,:] = xxf[0]*100
  1711. elif filtup[list(intup).index(stateli[i1])] == 2:
  1712. stateli[i1] = stateli[i1]+'(bkf)'
  1713. xx = sim_x[i1,:].__array__().T
  1714. wox = np.zeros((tlen,1))
  1715. up = 6
  1716. dn = 32
  1717. kkl = 12
  1718. xxf = MAT.matrix(bkfilter(xx,up,dn,kkl,tlen))
  1719. sim_x[i1,:] = xxf[0]*100
  1720. # Now hp filter the other variables!
  1721. if self.oswitch:
  1722. for i1 in xrange(sim_o.shape[0]):
  1723. if indo and (i1 in indo) and filtup[list(intup).index(otherli[i1])]:
  1724. if filtup[list(intup).index(otherli[i1])] == 1:
  1725. otherli[i1] = otherli[i1]+'(hpf)'
  1726. oo = sim_o[i1,:].__array__().T
  1727. woo = np.zeros((tlen,3))
  1728. lam = 1600
  1729. oof = MAT.matrix(hpfilter(data=oo,lam=1600))
  1730. elif filtup[list(intup).index(otherli[i1])] == 2:
  1731. otherli[i1] = otherli[i1]+'(bkf)'
  1732. oo = sim_o[i1,:].__array__().T
  1733. woo = np.zeros((tlen,1))
  1734. up = 6
  1735. dn = 32
  1736. kkl = 12
  1737. oof = MAT.matrix(bkfilter(oo,up,dn,kkl,tlen))
  1738. if indx and indy and indo:
  1739. for x in indx:
  1740. leg.append(stateli[x])
  1741. for y in indy:
  1742. leg.append(conli[y])
  1743. for o in indo:
  1744. leg.append(otherli[o])
  1745. leg = tuple(leg)
  1746. figo = P.figure()
  1747. P.plot(MAT.hstack((sim_x.T[:,indx],sim_y.T[:,indy],sim_o.T[:,indo])).A)
  1748. P.title(str(tlen)+' simulated periods, '+mname)
  1749. P.xlabel('Time')
  1750. P.ylabel('Percentage deviation from SS')
  1751. P.grid()
  1752. P.legend(leg)
  1753. elif not indx and indy and indo:
  1754. for y in indy:
  1755. leg.append(conli[y])
  1756. for o in indo:
  1757. leg.append(otherli[o])
  1758. leg = tuple(leg)
  1759. figo = P.figure()
  1760. P.plot(MAT.hstack((sim_y.T[:,indy],sim_o.T[:,indo])).A)
  1761. P.title(str(tlen)+' simulated periods, '+mname)
  1762. P.xlabel('Time')
  1763. P.ylabel('Percentage deviation from SS')
  1764. P.grid()
  1765. P.legend(leg)
  1766. elif indx and not indy and indo:
  1767. for x in indx:
  1768. leg.append(stateli[x])
  1769. for o in indo:
  1770. leg.append(otherli[o])
  1771. leg = tuple(leg)
  1772. figo = P.figure()
  1773. P.plot(MAT.hstack((sim_x.T[:,indx],sim_o.T[:,indo])).A)
  1774. P.title(str(tlen)+' simulated periods, '+mname)
  1775. P.xlabel('Time')
  1776. P.ylabel('Percentage deviation from SS')
  1777. P.grid()
  1778. P.legend(leg)
  1779. elif indx and indy and not indo:
  1780. for x in indx:
  1781. leg.append(stateli[x])
  1782. for y in indy:
  1783. leg.append(conli[y])
  1784. leg = tuple(leg)
  1785. figo = P.figure()
  1786. P.plot(MAT.hstack((sim_x.T[:,indx],sim_y.T[:,indy])).A)
  1787. P.title(str(tlen)+' simulated periods, '+mname)
  1788. P.xlabel('Time')
  1789. P.ylabel('Percentage deviation from SS')
  1790. P.grid()
  1791. P.legend(leg)
  1792. elif indx and not indy and not indo:
  1793. for x in indx:
  1794. leg.append(stateli[x])
  1795. leg = tuple(leg)
  1796. figo = P.figure()
  1797. P.plot(sim_x.T[:,indx].A)
  1798. P.title(str(tlen)+' simulated periods, '+mname)
  1799. P.xlabel('Time')
  1800. P.ylabel('Percentage deviation from SS')
  1801. P.grid()
  1802. P.legend(leg)
  1803. elif not indx and indy and not indo:
  1804. for y in indy:
  1805. leg.append(conli[y])
  1806. leg = tuple(leg)
  1807. figo = P.figure()
  1808. P.plot(sim_y.T[:,indy].A)
  1809. P.title(str(tlen)+' simulated periods, '+mname)
  1810. P.xlabel('Time')
  1811. P.ylabel('Percentage deviation from SS')
  1812. P.grid()
  1813. P.legend(leg)
  1814. elif not indx and not indy and indo:
  1815. for o in indo:
  1816. leg.append(otherli[o])
  1817. leg = tuple(leg)
  1818. figo = P.figure()
  1819. P.plot(sim_o.T[:,indo].A)
  1820. P.title(str(tlen)+' simulated periods, '+mname)
  1821. P.xlabel('Time')
  1822. P.ylabel('Percentage deviation from SS')
  1823. P.grid()
  1824. P.legend(leg)
  1825. PLT.savefig(fpath,dpi=100)
  1826. return "Your plot has been saved in: "+fpath
  1827. def irf(self,tlen,sntup,shockmod=None):
  1828. # Deals with 0-tuples
  1829. if type(sntup) != type((1,2,3)) and type(sntup) == type('abc'):
  1830. sntup = (sntup,)
  1831. # Deal with shockmod, also take care of 0-tuples by turning all into lists
  1832. if shockmod != None and type(shockmod) != type((1,2,3)) and type(shockmod) == type(1.0):
  1833. shockmod = [shockmod,]
  1834. elif shockmod != None and len(shockmod) > 1:
  1835. shockmod = [x for x in shockmod]
  1836. elif shockmod == None:
  1837. shockmod = [1.0,]*len(sntup)
  1838. tlen = tlen + 1
  1839. ncon = self.ncon
  1840. nexo = self.nexo
  1841. nendo = self.nendo
  1842. tstates = self.tstates
  1843. sigma = self.sigma
  1844. ssigma = self.ssigma
  1845. if self.oswitch:
  1846. numjl = self.numjl
  1847. numhl = self.numhl
  1848. kx = self.KX
  1849. ky = self.KY
  1850. pp = self.P
  1851. ff = self.F
  1852. ee = self.E
  1853. gg = self.G
  1854. sposli=[]
  1855. exoli = [x[1] for x in self.vardic['exo']['var']]
  1856. # Check if names are valid
  1857. for name in sntup:
  1858. if name not in exoli:
  1859. return 'Error: '+name+' is not a valid exoshock name for this model!'
  1860. for name in sntup:
  1861. sposli.append(exoli.index(name))
  1862. # Expose spos choice to self for show_irf
  1863. self.spos = (sntup,sposli)
  1864. shock = MAT.zeros((nexo,1))
  1865. sendo = MAT.zeros((nendo,1))
  1866. for i1,spos in enumerate(sposli):
  1867. shock[spos,0] = 1.0*shockmod[i1]
  1868. shock = MAT.vstack((shock,sendo))
  1869. self.sshock = COP.deepcopy(shock)
  1870. x_one_m1 = shock
  1871. x_one_0 = pp*x_one_m1
  1872. x_two_m1 = shock
  1873. y_one_0 = ff*x_one_m1
  1874. # Because they are jump variables
  1875. y_one_m1 = MAT.zeros(y_one_0.shape)
  1876. y_two_0 = 0.5*MAT.kron(MAT.eye(ncon),x_one_m1.T)*ee*x_one_m1
  1877. if self.oswitch:
  1878. nother = self.nother
  1879. o_one_0 = numjl*MAT.vstack((x_one_0,y_one_0,x_one_m1,y_one_m1))
  1880. o_two_0 = numjl*MAT.vstack((x_one_0,y_one_0,x_one_m1,y_one_m1))+\
  1881. 0.5*MAT.kron(MAT.eye(nother),MAT.vstack((x_one_0,y_one_0,x_one_m1,y_one_m1)).T)*\
  1882. numhl*MAT.vstack((x_one_0,y_one_0,x_one_m1,y_one_m1))
  1883. x_one_c = COP.deepcopy(x_one_m1)
  1884. y_one_c = COP.deepcopy(y_one_0)
  1885. x_two_c = COP.deepcopy(x_two_m1)
  1886. y_two_c = COP.deepcopy(y_two_0)
  1887. if self.oswitch:
  1888. o_one_c = COP.deepcopy(o_one_0)
  1889. o_two_c = COP.deepcopy(o_two_0)
  1890. x_one = COP.deepcopy(x_one_c)
  1891. y_one = COP.deepcopy(y_one_c)
  1892. x_two = COP.deepcopy(x_two_c)
  1893. y_two = COP.deepcopy(y_two_c)
  1894. if self.oswitch:
  1895. o_one = COP.deepcopy(o_one_c)
  1896. o_two = COP.deepcopy(o_two_c)
  1897. for i1 in range(tlen):
  1898. x_one_n = pp*x_one_c
  1899. y_one_n = ff*x_one_c
  1900. x_two_n = pp*x_two_c+0.5*MAT.kron(MAT.eye(tstates),x_one_c.T)*gg*x_one_c
  1901. y_two_n = ff*x_two_c+0.5*MAT.kron(MAT.eye(ncon),x_one_c.T)*ee*x_one_c
  1902. if self.oswitch:
  1903. o_one_n = numjl*MAT.vstack((x_one_n,y_one_n,x_one_c,y_one_c))
  1904. o_two_n = numjl*MAT.vstack((x_one_n,y_one_n,x_one_c,y_one_c))+\
  1905. 0.5*MAT.kron(MAT.eye(nother),MAT.vstack((x_one_n,y_one_n,x_one_c,y_one_c)).T)*\
  1906. numhl*MAT.vstack((x_one_n,y_one_n,x_one_c,y_one_c))
  1907. x_one = MAT.hstack((x_one,x_one_c))
  1908. y_one = MAT.hstack((y_one,y_one_n))
  1909. x_two = MAT.hstack((x_two,x_two_c))
  1910. y_two = MAT.hstack((y_two,y_two_n))
  1911. if self.oswitch:
  1912. o_one = MAT.hstack((o_one,o_one_n))
  1913. o_two = MAT.hstack((o_two,o_two_n))
  1914. x_one_c = COP.deepcopy(x_one_n)
  1915. y_one_c = COP.deepcopy(y_one_n)
  1916. x_two_c = COP.deepcopy(x_one_n)
  1917. y_two_c = COP.deepcopy(y_two_n)
  1918. self.irf_x_two = x_two[:,1:-1]
  1919. self.irf_y_two = y_two[:,1:-1]
  1920. self.inirf = [self.irf_x_two,self.irf_y_two]
  1921. if self.oswitch:
  1922. self.irf_o_one = o_one[:,2:]
  1923. self.irf_o_two = o_two[:,2:]
  1924. self.inirf = self.inirf + [self.irf_o_two,]
  1925. def show_irf(self,intup,inirf='inirf'):
  1926. # Check if simulations have been carried out
  1927. if inirf not in dir(self):
  1928. return 'Error: You have not produced any IRFs yet! Nothing to graph!'
  1929. inirf = eval('self.'+inirf)
  1930. irf_x = COP.deepcopy(inirf[0])
  1931. tlen = irf_x.shape[1]
  1932. irf_x = MAT.hstack((MAT.zeros((irf_x.shape[0],20)),irf_x))
  1933. irf_y = COP.deepcopy(inirf[1])
  1934. irf_y = MAT.hstack((MAT.zeros((irf_y.shape[0],20)),irf_y))
  1935. #irf_x = irf_x*100.0
  1936. #irf_y = irf_y*100.0
  1937. mname = self.modname
  1938. vardic = self.vardic
  1939. time_axis = np.arange(-20,tlen,1)
  1940. if self.oswitch:
  1941. irf_o = COP.deepcopy(inirf[2])
  1942. irf_o = MAT.hstack((MAT.zeros((irf_o.shape[0],20)),irf_o))
  1943. nother = self.nother
  1944. varother = self.vardic['other']['var']
  1945. otherli = [x[1] for x in varother]
  1946. nexo = self.nexo
  1947. nendo = self.nendo
  1948. ncon = self.ncon
  1949. conli = [x[1] for x in vardic['con']['var']]
  1950. endoli = [x[1] for x in vardic['endo']['var']]
  1951. exoli = [x[1] for x in vardic['exo']['var']]
  1952. stateli = exoli+endoli
  1953. alli = stateli+conli
  1954. if self.oswitch:
  1955. alli = alli+otherli
  1956. # Check if all name in intup are available to graph
  1957. for name in intup:
  1958. if name not in alli:
  1959. return 'Error: '+name+' is not a valid variable name for this model!'
  1960. # Create x, y and z indeces
  1961. indx = []
  1962. indy = []
  1963. indo = []
  1964. for name in intup:
  1965. if name in stateli:
  1966. indx.append(stateli.index(name))
  1967. elif name in conli:
  1968. indy.append(conli.index(name))
  1969. elif self.oswitch and name in otherli:
  1970. indo.append(otherli.index(name))
  1971. leg = []
  1972. indx.sort()
  1973. indy.sort()
  1974. indo.sort()
  1975. if indx and indy and indo:
  1976. for x in indx:
  1977. leg.append(stateli[x])
  1978. for y in indy:
  1979. leg.append(conli[y])
  1980. for o in indo:
  1981. leg.append(otherli[o])
  1982. leg = tuple(leg)
  1983. figo = P.figure()
  1984. ax = figo.add_subplot(111)
  1985. ax.set_xlim([-20,tlen])
  1986. ax.plot(time_axis,MAT.hstack((irf_x.T[:,indx],irf_y.T[:,indy],irf_o.T[:,indo])).A)
  1987. P.title(str(tlen)+' IRF periods, '+mname)
  1988. P.xlabel('Time')
  1989. P.ylabel('Percentage Deviation from SS')
  1990. P.grid()
  1991. P.legend(leg)
  1992. elif not indx and indy and indo:
  1993. for y in indy:
  1994. leg.append(conli[y])
  1995. for o in indo:
  1996. leg.append(otherli[o])
  1997. leg = tuple(leg)
  1998. figo = P.figure()
  1999. ax = figo.add_subplot(111)
  2000. ax.set_xlim([-20,tlen])
  2001. ax.plot(time_axis,MAT.hstack((irf_y.T[:,indy],irf_o.T[:,indo])).A)
  2002. P.title(str(tlen)+' IRF periods, '+mname)
  2003. P.xlabel('Time')
  2004. P.ylabel('Percentage Deviation from SS')
  2005. P.grid()
  2006. P.legend(leg)
  2007. elif indx and not indy and indo:
  2008. for x in indx:
  2009. leg.append(stateli[x])
  2010. for o in indo:
  2011. leg.append(otherli[o])
  2012. leg = tuple(leg)
  2013. figo = P.figure()
  2014. ax = figo.add_subplot(111)
  2015. ax.set_xlim([-20,tlen])
  2016. ax.plot(time_axis,MAT.hstack((irf_x.T[:,indx],irf_o.T[:,indo])).A)
  2017. P.title(str(tlen)+' IRF periods, '+mname)
  2018. P.xlabel('Time')
  2019. P.ylabel('Percentage Deviation from SS')
  2020. P.grid()
  2021. P.legend(leg)
  2022. elif indx and indy and not indo:
  2023. for x in indx:
  2024. leg.append(stateli[x])
  2025. for y in indy:
  2026. leg.append(conli[y])
  2027. leg = tuple(leg)
  2028. figo = P.figure()
  2029. ax = figo.add_subplot(111)
  2030. ax.set_xlim([-20,tlen])
  2031. ax.plot(time_axis,MAT.hstack((irf_x.T[:,indx],irf_y.T[:,indy])).A)
  2032. P.title(str(tlen)+' IRF periods, '+mname)
  2033. P.xlabel('Time')
  2034. P.ylabel('Percentage Deviation from SS')
  2035. P.grid()
  2036. P.legend(leg)
  2037. elif indx and not indy and not indo:
  2038. for x in indx:
  2039. leg.append(stateli[x])
  2040. leg = tuple(leg)
  2041. figo = P.figure()
  2042. ax = figo.add_subplot(111)
  2043. ax.set_xlim([-20,tlen])
  2044. ax.plot(time_axis,irf_x.T[:,indx].A)
  2045. P.title(str(tlen)+' IRF periods, '+mname)
  2046. P.xlabel('Time')
  2047. P.ylabel('Percentage Deviation from SS')
  2048. P.grid()
  2049. P.legend(leg)
  2050. elif not indx and indy and not indo:
  2051. for y in indy:
  2052. leg.append(conli[y])
  2053. leg = tuple(leg)
  2054. figo = P.figure()
  2055. ax = figo.add_subplot(111)
  2056. ax.set_xlim([-20,tlen])
  2057. ax.plot(time_axis,irf_y.T[:,indy].A)
  2058. P.title(str(tlen)+' IRF periods, '+mname)
  2059. P.xlabel('Time')
  2060. P.ylabel('Percentage Deviation from SS')
  2061. P.grid()
  2062. P.legend(leg)
  2063. elif not indx and not indy and indo:
  2064. for o in indo:
  2065. leg.append(otherli[o])
  2066. leg = tuple(leg)
  2067. figo = P.figure()
  2068. ax = figo.add_subplot(111)
  2069. ax.set_xlim([-20,tlen])
  2070. ax.plot(time_axis,irf_o.T[:,indo].A)
  2071. P.title(str(tlen)+' IRF periods, '+mname)
  2072. P.xlabel('Time')
  2073. P.ylabel('Percentage Deviation from SS')
  2074. P.grid()
  2075. P.legend(leg)
  2076. return figo
  2077. def save_irf(self,intup,fpath=None,inirf='inirf'):
  2078. # Check if simulations have been carried out
  2079. if inirf not in dir(self):
  2080. return 'Error: You have not produced any IRFs yet! Nothing to graph!'
  2081. if fpath == None:
  2082. return 'Error: You have not supplied the function with an fpath= argument where to save the plot!'
  2083. inirf = eval('self.'+inirf)
  2084. irf_x = COP.deepcopy(inirf[0])
  2085. tlen = irf_x.shape[1]
  2086. irf_x = MAT.hstack((MAT.zeros((irf_x.shape[0],20)),irf_x))
  2087. irf_y = COP.deepcopy(inirf[1])
  2088. irf_y = MAT.hstack((MAT.zeros((irf_y.shape[0],20)),irf_y))
  2089. irf_x = irf_x*100
  2090. irf_y = irf_y*100
  2091. mname = self.modname
  2092. vardic = self.vardic
  2093. time_axis = np.arange(-20,tlen,1)
  2094. if self.oswitch:
  2095. irf_o = COP.deepcopy(inirf[2])
  2096. nother = self.nother
  2097. varother = self.vardic['other']['var']
  2098. otherli = [x[1] for x in varother]
  2099. nexo = self.nexo
  2100. nendo = self.nendo
  2101. ncon = self.ncon
  2102. conli = [x[1] for x in vardic['con']['var']]
  2103. endoli = [x[1] for x in vardic['endo']['var']]
  2104. exoli = [x[1] for x in vardic['exo']['var']]
  2105. stateli = exoli+endoli
  2106. alli = stateli+conli
  2107. if self.oswitch:
  2108. alli = alli+otherli
  2109. # Check if all name in intup are available to graph
  2110. for name in intup:
  2111. if name not in alli:
  2112. return 'Error: '+name+' is not a valid variable name for this model!'
  2113. # Create x, y and z indeces
  2114. indx = []
  2115. indy = []
  2116. indo = []
  2117. for name in intup:
  2118. if name in stateli:
  2119. indx.append(stateli.index(name))
  2120. elif name in conli:
  2121. indy.append(conli.index(name))
  2122. elif self.oswitch and name in otherli:
  2123. indo.append(otherli.index(name))
  2124. leg = []
  2125. indx.sort()
  2126. indy.sort()
  2127. indo.sort()
  2128. if indx and indy and indo:
  2129. for x in indx:
  2130. leg.append(stateli[x])
  2131. for y in indy:
  2132. leg.append(conli[y])
  2133. for o in indo:
  2134. leg.append(otherli[o])
  2135. leg = tuple(leg)
  2136. figo = P.figure()
  2137. ax = figo.add_subplot(111)
  2138. ax.set_xlim([-20,tlen])
  2139. ax.plot(time_axis,MAT.hstack((irf_x.T[:,indx],irf_y.T[:,indy],irf_o.T[:,indo])).A)
  2140. P.title(str(tlen)+' simulated IRF periods, '+mname)
  2141. P.xlabel('Time')
  2142. P.ylabel('Percentage Deviation from SS')
  2143. P.grid()
  2144. P.legend(leg)
  2145. elif not indx and indy and indo:
  2146. for y in indy:
  2147. leg.append(conli[y])
  2148. for o in indo:
  2149. leg.append(otherli[o])
  2150. leg = tuple(leg)
  2151. figo = P.figure()
  2152. ax = figo.add_subplot(111)
  2153. ax.set_xlim([-20,tlen])
  2154. ax.plot(time_axis,MAT.hstack((irf_y.T[:,indy],irf_o.T[:,indo])).A)
  2155. P.title(str(tlen)+' simulated IRF periods, '+mname)
  2156. P.xlabel('Time')
  2157. P.ylabel('Percentage Deviation from SS')
  2158. P.grid()
  2159. P.legend(leg)
  2160. elif indx and not indy and indo:
  2161. for x in indx:
  2162. leg.append(stateli[x])
  2163. for o in indo:
  2164. leg.append(otherli[o])
  2165. leg = tuple(leg)
  2166. figo = P.figure()
  2167. ax = figo.add_subplot(111)
  2168. ax.set_xlim([-20,tlen])
  2169. ax.plot(time_axis,MAT.hstack((irf_x.T[:,indx],irf_o.T[:,indo])).A)
  2170. P.title(str(tlen)+' simulated IRF periods, '+mname)
  2171. P.xlabel('Time')
  2172. P.ylabel('Percentage Deviation from SS')
  2173. P.grid()
  2174. P.legend(leg)
  2175. elif indx and indy and not indo:
  2176. for x in indx:
  2177. leg.append(stateli[x])
  2178. for y in indy:
  2179. leg.append(conli[y])
  2180. leg = tuple(leg)
  2181. figo = P.figure()
  2182. ax = figo.add_subplot(111)
  2183. ax.set_xlim([-20,tlen])
  2184. ax.plot(time_axis,MAT.hstack((irf_x.T[:,indx],irf_y.T[:,indy])).A)
  2185. P.title(str(tlen)+' simulated IRF periods, '+mname)
  2186. P.xlabel('Time')
  2187. P.ylabel('Percentage Deviation from SS')
  2188. P.grid()
  2189. P.legend(leg)
  2190. elif indx and not indy and not indo:
  2191. for x in indx:
  2192. leg.append(stateli[x])
  2193. leg = tuple(leg)
  2194. figo = P.figure()
  2195. ax = figo.add_subplot(111)
  2196. ax.set_xlim([-20,tlen])
  2197. ax.plot(time_axis,irf_x.T[:,indx].A)
  2198. P.title(str(tlen)+' simulated IRF periods, '+mname)
  2199. P.xlabel('Time')
  2200. P.ylabel('Percentage Deviation from SS')
  2201. P.grid()
  2202. P.legend(leg)
  2203. elif not indx and indy and not indo:
  2204. for y in indy:
  2205. leg.append(conli[y])
  2206. leg = tuple(leg)
  2207. figo = P.figure()
  2208. ax = figo.add_subplot(111)
  2209. ax.set_xlim([-20,tlen])
  2210. ax.plot(time_axis,irf_y.T[:,indy].A)
  2211. P.title(str(tlen)+' simulated IRF periods, '+mname)
  2212. P.xlabel('Time')
  2213. P.ylabel('Percentage Deviation from SS, hp-filtered')
  2214. P.grid()
  2215. P.legend(leg)
  2216. elif not indx and not indy and indo:
  2217. for o in indo:
  2218. leg.append(otherli[o])
  2219. leg = tuple(leg)
  2220. figo = P.figure()
  2221. ax = figo.add_subplot(111)
  2222. ax.set_xlim([-20,tlen])
  2223. ax.plot(time_axis,irf_o.T[:,indo].A)
  2224. P.title(str(tlen)+' simulated IRF periods, '+mname)
  2225. P.xlabel('Time')
  2226. P.ylabel('Percentage Deviation from SS, hp-filtered')
  2227. P.grid()
  2228. P.legend(leg)
  2229. PLT.savefig(fpath,dpi=100)
  2230. return "Your plot has been save in: "+fpath
  2231. #----------------------------------------------------------------------------------------------------------------------
  2232. class MatKlein2D(PyKlein2D):
  2233. def __init__(self,intup):
  2234. self.sess1 = intup[-1]
  2235. intup2 = intup[:-1]
  2236. # Get all PyKlein2D attributes
  2237. PyKlein2D.__init__(self, intup2)
  2238. def solve(self):
  2239. tstates = self.tstates
  2240. sess1 = self.sess1
  2241. ssigma = self.ssigma
  2242. mlabraw.eval(sess1,'clear all;')
  2243. mlabraw.eval(sess1,'cd '+mlabpath)
  2244. mlabraw.eval(sess1,'cd Klein')
  2245. mlabraw.put(sess1,'jac',self.gra)
  2246. mlabraw.put(sess1,'hess',self.hes)
  2247. mlabraw.put(sess1,'nstates',self.tstates)
  2248. mlabraw.put(sess1,'ssigma',self.ssigma)
  2249. mlabraw.eval(sess1,'[ff,pp,ee,gg,kx,ky] = solab2(jac,hess,ssigma,nstates)')
  2250. self.F = np.matrix(mlabraw.get(sess1,'ff'))
  2251. self.P = np.matrix(mlabraw.get(sess1,'pp'))
  2252. self.E = np.matrix(mlabraw.get(sess1,'ee'))
  2253. self.G = np.matrix(mlabraw.get(sess1,'gg'))
  2254. self.KX = np.matrix(mlabraw.get(sess1,'kx'))
  2255. self.KY = np.matrix(mlabraw.get(sess1,'ky'))
  2256. #----------------------------------------------------------------------------------------------------------------------
  2257. class ForKleinD(PyKlein2D):
  2258. def __init__(self,intup,other=None):
  2259. if other != None:
  2260. self.other = other
  2261. self.gra = intup[0]
  2262. self.nendo = intup[1]
  2263. self.nexo = intup[2]
  2264. self.ncon = intup[3]
  2265. self.sigma = intup[4]
  2266. self.A = intup[5]
  2267. self.B = intup[6]
  2268. self.vardic = intup[7]
  2269. self.vdic = intup[8]
  2270. self.modname = intup[9]
  2271. self.audic = intup[10]
  2272. if self.vardic['other']['var']:
  2273. self.numjl = intup[11]
  2274. self.nother = intup[12]
  2275. self.oswitch = 1
  2276. else:
  2277. self.oswitch = 0
  2278. self.tstates = self.nendo+self.nexo
  2279. self.ssigma = self.mkssigma(self.tstates,self.nexo,self.sigma)
  2280. def solve(self):
  2281. A = self.A
  2282. B = self.B
  2283. tstates = self.tstates
  2284. (F,P,alpha,betta,retcon) = isolab(A,B,tstates,MAT.shape(A)[0])
  2285. self.alpha = abs(alpha)
  2286. self.betta = abs(betta)
  2287. if MAT.sum(P.reshape(-1,1)) == 0.0:
  2288. return
  2289. else:
  2290. self.P = np.matrix(P)
  2291. self.F = np.matrix(F)
  2292. def sim(self,tlen,sntup=None,shockvec=None):
  2293. # Deals with 0-tuples
  2294. if type(sntup) != type((1,2,3)) and type(sntup) == type('abc'):
  2295. sntup = (sntup,)
  2296. # Add 1000 observations, as they will be thrown away
  2297. # Add one more observation to start first-order vector
  2298. exoli = [x[1] for x in self.vardic['exo']['var']]
  2299. indx=[]
  2300. if sntup == None:
  2301. indx = range(len(exoli))
  2302. else:
  2303. for name in sntup:
  2304. if name not in exoli:
  2305. return 'Error: '+name+' is not a valid exo variable for this model!'
  2306. else:
  2307. indx.append(exoli.index(name))
  2308. indx.sort()
  2309. ncon = self.ncon
  2310. nexo = self.nexo
  2311. nendo = self.nendo
  2312. tstates = self.tstates
  2313. tlena = 1000+tlen
  2314. sigma = self.sigma
  2315. ssigma = self.ssigma
  2316. if self.oswitch:
  2317. numjl = self.numjl
  2318. pp = self.P
  2319. ff = self.F
  2320. if shockvec == None:
  2321. count = 0
  2322. for varia in MAT.diag(sigma):
  2323. if locals().has_key('ranvec'):
  2324. if count in indx:
  2325. ranvec = MAT.vstack((ranvec,np.sqrt(varia)*MAT.matrix(np.random.standard_normal(tlena))))
  2326. else:
  2327. ranvec = MAT.vstack((ranvec,MAT.zeros((1,tlena))))
  2328. else:
  2329. if count in indx:
  2330. ranvec = np.sqrt(varia)*MAT.matrix(np.random.standard_normal(tlena))
  2331. else:
  2332. ranvec = MAT.zeros((1,tlena))
  2333. count = count + 1
  2334. ranvec = MAT.vstack((ranvec,MAT.zeros((nendo,tlena))))
  2335. # Save the random shocks vector
  2336. self.shockvec = COP.deepcopy(ranvec)
  2337. else:
  2338. ranvec = COP.deepcopy(shockvec)
  2339. x_one_m1 = ranvec[:,0]
  2340. y_one_0 = ff*x_one_m1
  2341. y_one_m1 = MAT.zeros(y_one_0.shape)
  2342. x_one_0 = pp*x_one_m1
  2343. if self.oswitch:
  2344. nother = self.nother
  2345. o_one_0 = numjl*MAT.vstack((x_one_0,y_one_0,x_one_m1,y_one_m1))
  2346. x_one_c = COP.deepcopy(x_one_m1)
  2347. y_one_c = COP.deepcopy(y_one_0)
  2348. if self.oswitch:
  2349. o_one_c = COP.deepcopy(o_one_0)
  2350. x_one = COP.deepcopy(x_one_c)
  2351. y_one = COP.deepcopy(y_one_c)
  2352. if self.oswitch:
  2353. o_one = COP.deepcopy(o_one_c)
  2354. for i1 in range(1,ranvec.shape[1],1):
  2355. x_one_n = pp*x_one_c+ranvec[:,i1]
  2356. y_one_n = ff*x_one_c
  2357. if self.oswitch:
  2358. o_one_n = numjl*MAT.vstack((x_one_n,y_one_n,x_one_c,y_one_c))
  2359. x_one = MAT.hstack((x_one,x_one_c))
  2360. y_one = MAT.hstack((y_one,y_one_n))
  2361. if self.oswitch:
  2362. o_one = MAT.hstack((o_one,o_one_n))
  2363. x_one_c = x_one_n
  2364. y_one_c = y_one_n
  2365. # Throw away first 1000 obs
  2366. x_one = x_one[:,1000:]
  2367. y_one = y_one[:,1000:]
  2368. if self.oswitch:
  2369. o_one = o_one[:,1000:]
  2370. self.sim_x_one = x_one
  2371. self.sim_y_one = y_one
  2372. self.insim = [self.sim_x_one,self.sim_y_one]
  2373. if self.oswitch:
  2374. self.sim_o_one = o_one
  2375. self.insim = self.insim + [self.sim_o_one,]
  2376. def irf(self,tlen,sntup=None,shockmod=None):
  2377. # Deals with 0-tuples
  2378. if type(sntup) != type((1,2,3)) and type(sntup) == type('abc'):
  2379. sntup = (sntup,)
  2380. # Deal with shockmod, also take care of 0-tuples by turning all into lists
  2381. if shockmod != None and type(shockmod) != type((1,2,3)) and type(shockmod) == type(1.0):
  2382. shockmod = [shockmod,]
  2383. elif shockmod != None and len(shockmod) > 1:
  2384. shockmod = [x for x in shockmod]
  2385. elif shockmod == None:
  2386. shockmod = [1.0,]*len(sntup)
  2387. tlen = tlen + 1
  2388. ncon = self.ncon
  2389. nexo = self.nexo
  2390. nendo = self.nendo
  2391. tstates = self.tstates
  2392. sigma = self.sigma
  2393. ssigma = self.ssigma
  2394. tlen = tlen
  2395. if self.oswitch:
  2396. numjl = self.numjl
  2397. pp = self.P
  2398. ff = self.F
  2399. sposli=[]
  2400. exoli = [x[1] for x in self.vardic['exo']['var']]
  2401. # Check if names are valid
  2402. for name in sntup:
  2403. if name not in exoli:
  2404. return 'Error: '+name+' is not a valid exoshock name for this model!'
  2405. for name in sntup:
  2406. sposli.append(exoli.index(name))
  2407. # Expose spos choice to self for show_irf
  2408. self.spos = (sntup,sposli)
  2409. shock = MAT.zeros((nexo,1))
  2410. sendo = MAT.zeros((nendo,1))
  2411. for i1,spos in enumerate(sposli):
  2412. shock[spos,0] = 1.0*shockmod[i1]
  2413. shock = MAT.vstack((shock,sendo))
  2414. '''
  2415. if shockvec == None:
  2416. for elem in range(ssigma.shape[0]):
  2417. ssigma[elem,elem] = np.sqrt(ssigma[elem,elem])
  2418. shock = np.dot(ssigma,shock)
  2419. else:
  2420. ssigma = self.mkssigma(self.tstates,self.nexo,shockvec)
  2421. for elem in range(ssigma.shape[0]):
  2422. ssigma[elem,elem] = np.sqrt(ssigma[elem,elem])
  2423. shock = np.dot(ssigma,shock)
  2424. '''
  2425. self.sshock = COP.deepcopy(shock)
  2426. x_one_m1 = shock
  2427. y_one_0 = ff*x_one_m1
  2428. y_one_m1 = MAT.zeros(y_one_0.shape)
  2429. x_one_0 = pp*x_one_m1
  2430. if self.oswitch:
  2431. nother = self.nother
  2432. o_one_0 = numjl*MAT.vstack((x_one_0,y_one_0,x_one_m1,y_one_m1))
  2433. x_one_c = COP.deepcopy(x_one_m1)
  2434. y_one_c = COP.deepcopy(y_one_0)
  2435. if self.oswitch:
  2436. o_one_c = COP.deepcopy(o_one_0)
  2437. x_one = COP.deepcopy(x_one_c)
  2438. y_one = COP.deepcopy(y_one_c)
  2439. if self.oswitch:
  2440. o_one = COP.deepcopy(o_one_c)
  2441. for i1 in range(tlen):
  2442. x_one_n = pp*x_one_c
  2443. y_one_n = ff*x_one_c
  2444. if self.oswitch:
  2445. o_one_n = numjl*MAT.vstack((x_one_n,y_one_n,x_one_c,y_one_c))
  2446. x_one = MAT.hstack((x_one,x_one_c))
  2447. y_one = MAT.hstack((y_one,y_one_n))
  2448. if self.oswitch:
  2449. o_one = MAT.hstack((o_one,o_one_n))
  2450. x_one_c = x_one_n
  2451. y_one_c = y_one_n
  2452. # Throw away first observation
  2453. self.irf_x_one = x_one[:,1:-1]
  2454. self.irf_y_one = y_one[:,1:-1]
  2455. self.inirf = [self.irf_x_one,self.irf_y_one]
  2456. if self.oswitch:
  2457. self.irf_o_one = o_one[:,2:]
  2458. self.inirf = self.inirf + [self.irf_o_one,]
  2459. #------------------------currently not called and really not working, removed from init----------------
  2460. class FairTaylor:
  2461. def __init__(self,algtype='type1',intup=None):
  2462. self.algtype = algtype
  2463. self.data = intup[0]
  2464. self.param = intup[1]
  2465. self.sstates_list = intup[2]
  2466. self.vardic = intup[3]
  2467. self.vardic2 = intup[4]
  2468. self.modeq = intup[5]
  2469. self.maxlags = intup[6]
  2470. self.maxleads = intup[7]
  2471. self.maxshocks = intup[8]
  2472. self.maxinfosets = intup[9]
  2473. self.shock_vars = intup[10]
  2474. self.iid_vars = intup[11]
  2475. self.vars = intup[12]
  2476. self.re_var = intup[13]
  2477. self.re_var2 = intup[14]
  2478. self.sstate = intup[15]
  2479. self.prepdat(self.data)
  2480. self.prepmodeq(self.modeq)
  2481. def prepdat(self,data=None):
  2482. self.cur_pres = {}
  2483. self.cur_past = {}
  2484. self.cur_fut = {}
  2485. for x1 in data.items():
  2486. self.cur_pres[x1[0]] = x1[1][self.maxlags:len(x1[1])-self.maxleads]
  2487. self.cur_past[x1[0]] = x1[1][0:-2]
  2488. self.cur_fut[x1[0]] = x1[1][2:]
  2489. def prepmodeq(self,modeq=None):
  2490. re_var2 = self.re_var2
  2491. self.modeq1 = COP.deepcopy(modeq)
  2492. tmp_list = []
  2493. i1 = 0
  2494. for x1 in modeq:
  2495. itera = re_var2.finditer(x1)
  2496. for x2 in itera:
  2497. if x2.group('svar'):
  2498. tmp_list = tmp_list + [[i1,x2.group('svar'),x2.start(),x2.end()],]
  2499. i1 = i1 + 1
  2500. tmp_list.reverse()
  2501. if tmp_list:
  2502. for x2 in tmp_list:
  2503. i1 = x2[0]
  2504. expr = x2[1]
  2505. estart = x2[2]
  2506. eend = x2[3]
  2507. x1 = self.modeq1[i1][0:estart]+expr.capitalize()+\
  2508. '_bar'+self.modeq1[i1][eend:]
  2509. self.modeq1[i1] = x1
  2510. self.modeq2 = self.modeq1[0:len(modeq)-self.maxshocks]
  2511. self.modeq3 = COP.deepcopy(self.modeq2)
  2512. # Create varlist from vardic to establish fixed order
  2513. self.varlist = self.vardic.items()
  2514. # Create ordered vars and varnames
  2515. varnames = []
  2516. variables = []
  2517. sub_list1 = []
  2518. sub_list2 = []
  2519. tmp_index = {}
  2520. for x1 in self.varlist:
  2521. varnames = varnames + [x1[1],]
  2522. variables = variables + [x1[0],]
  2523. self.varnames = varnames
  2524. self.variables = variables
  2525. re_var2 = self.re_var2
  2526. i1 = 0
  2527. i2 = 0
  2528. for x1 in self.modeq2:
  2529. itera = re_var2.finditer(x1)
  2530. for x2 in itera:
  2531. if x2.group('vvar') and not x2.group('exp') and not x2.group('lagt'):
  2532. tmp_match = variables.index(x2.group('var'))
  2533. if not tmp_index.has_key(x2.group('var')):
  2534. tmp_index[x2.group('var')] = (i2,x2.group(0))
  2535. i2 = i2 + 1
  2536. sub_list1 = sub_list1 + [['invar['+str(tmp_index[x2.group('var')][0])+']',
  2537. x2.start(),x2.end(),x2.group(0),tmp_match,i1],]
  2538. sub_list1.reverse()
  2539. if sub_list1:
  2540. for x4 in sub_list1:
  2541. str_tmp = x4[0]
  2542. pstart = x4[1]
  2543. pend = x4[2]
  2544. self.modeq3[i1] = self.modeq3[i1][0:pstart]+str_tmp+self.modeq3[i1][pend:]
  2545. sub_list2 = sub_list2 + [sub_list1,]
  2546. sub_list1 = []
  2547. i1 = i1 + 1
  2548. self.index = tmp_index
  2549. # Create inverted index2
  2550. index2 = {}
  2551. for x1 in self.index.items():
  2552. index2[x1[1][0]] = (x1[0],x1[1][1])
  2553. self.index2 = index2
  2554. return sub_list2
  2555. def makecur(self,tpos,curlag,curpres,curfut):
  2556. lag_dic={}
  2557. pres_dic={}
  2558. fut_dic={}
  2559. all_dic={}
  2560. for x1 in curlag.items():
  2561. if float(x1[1][tpos].data) > 0:
  2562. lag_dic[self.vardic2[x1[0]]+'_L'] = float(x1[1][tpos].data)
  2563. else:
  2564. lag_dic[self.vardic2[x1[0]]+'_L'] = 0.01
  2565. for x1 in curpres.items():
  2566. if float(x1[1][tpos].data) > 0:
  2567. pres_dic[self.vardic2[x1[0]]+'_N'] = float(x1[1][tpos].data)
  2568. else:
  2569. pres_dic[self.vardic2[x1[0]]+'_N'] = 0.01
  2570. for x1 in curfut.items():
  2571. if float(x1[1][tpos].data) > 0:
  2572. fut_dic['INFO_N_'+self.vardic2[x1[0]]+'_F'] = float(x1[1][tpos].data)
  2573. else:
  2574. fut_dic['INFO_N_'+self.vardic2[x1[0]]+'_F'] = 0.01
  2575. all_dic.update(lag_dic)
  2576. all_dic.update(pres_dic)
  2577. all_dic.update(fut_dic)
  2578. self.alldic =all_dic
  2579. return all_dic
  2580. def solveone(self,tpos,curlag,curpres,curfut):
  2581. #Define the function to be handed over
  2582. #to fsolve
  2583. def func(invar):
  2584. locals().update(self.param)
  2585. locals().update(self.sstate[0])
  2586. locals().update(self.makecur(tpos,self.cur_past,self.cur_pres,self.cur_fut))
  2587. fdot1 = np.zeros((len(self.modeq3)),'d')
  2588. i1=0
  2589. for x in self.modeq3:
  2590. fdot1[i1] = eval(x)
  2591. i1 = i1 + 1
  2592. return fdot1
  2593. #def func(invar):
  2594. #locals().update(self.param)
  2595. #locals().update(self.sstate[0])
  2596. #locals().update(self.makecur(tpos,self.cur_past,self.cur_pres,self.cur_fut))
  2597. #fdot1 = np.zeros((len(self.modeq3)),'d')
  2598. #i1=0
  2599. #for x in self.modeq3:
  2600. #fdot1[i1] = abs(eval(x))
  2601. #i1 = i1 + 1
  2602. #return sum(fdot1)
  2603. #def fprime(invar):
  2604. #return np.array(([1,-1]))
  2605. # Define the initial values and
  2606. # start the non-linear solver
  2607. init_val = len(self.index)*[0,]
  2608. for x1 in self.index.items():
  2609. varia = self.vardic[x1[0]]['var']
  2610. init_val[x1[1][0]] = float(curpres[varia][tpos].data)
  2611. # Determine bounds
  2612. #in_bounds = len(self.index)*[(0.01,None),]
  2613. (output,infodict,ier,mesg) = O.fsolve(func,init_val,full_output=1)
  2614. #(output,f_out,d_out) = O.fmin_l_bfgs_b(func,init_val,
  2615. #fprime,approx_grad=True,bounds=in_bounds)
  2616. # Attach the outputs of the solver as attributes
  2617. fsout={}
  2618. self.output = output
  2619. i1 = 0
  2620. for x1 in self.index2.items():
  2621. fsout[x1[1][1]] = (output[x1[0]],x1[1][0])
  2622. i1 = i1 + 1
  2623. self.fsout = fsout
  2624. self.output = output
  2625. self.infodict = infodict
  2626. self.ier = ier
  2627. self.mesg = mesg
  2628. return fsout
  2629. def solveall(self):
  2630. # Calculate initial convergence criterion
  2631. criterion = 10
  2632. loop_c = 0
  2633. while criterion > 0.01:
  2634. cur_past_t = {}
  2635. cur_pres_t = {}
  2636. cur_fut_t = {}
  2637. for x1 in self.vardic2.items():
  2638. cur_past_t[x1[0]] = np.zeros(len(self.cur_pres.items()[0][1]))
  2639. cur_past_t[x1[0]][0] = float(self.cur_past[x1[0]][0].data)
  2640. cur_pres_t[x1[0]] = np.zeros(len(self.cur_pres.items()[0][1]))
  2641. cur_fut_t[x1[0]] = np.zeros(len(self.cur_pres.items()[0][1]))
  2642. cur_fut_t[x1[0]][-1] = float(self.cur_fut[x1[0]][-1].data)
  2643. for i1 in range(0,len(self.cur_pres.items()[0][1])):
  2644. out_tmp = self.solveone(i1,self.cur_past,self.cur_pres,self.cur_fut)
  2645. for x2 in out_tmp.items():
  2646. # Standard
  2647. if self.algtype == 'type1':
  2648. cur_pres_t[self.vardic[x2[1][1]['var']]][i1] = x2[1][0]
  2649. # Fast-Gauss Seidel
  2650. elif self.algtype == 'type2':
  2651. cur_pres_t[self.vardic[x2[1][1]['var']]][i1] = x2[1][0]
  2652. try:
  2653. self.cur_past[self.vardic[x2[1][1]['var']]][i1+1] = x2[1][0]
  2654. except:
  2655. pass
  2656. # Recalculate convergence criterion
  2657. cr_list = [0,]*len(self.vardic)
  2658. va_list = [0,]*len(self.vardic)
  2659. for x1,x2 in zip(self.vardic.items(),range(0,len(self.vardic),1)):
  2660. cr_list[x2] = cr_list[x2] + sum(abs(cur_fut_t[x1[1]][0:-1]-cur_pres_t[x1[1]][1:]))
  2661. va_list[x2] = x1[1]
  2662. criterion = sum(cr_list)
  2663. loop_c = loop_c + 1
  2664. print ('Loop: ',loop_c)
  2665. print ('Var: ',va_list)
  2666. print ('Crit: ',cr_list)
  2667. for x1 in self.vardic2.items():
  2668. cur_past_t[x1[0]][1:] = cur_pres_t[x1[0]][:-1]
  2669. cur_fut_t[x1[0]][0:-1] = cur_pres_t[x1[0]][1:]
  2670. for x1,x2,x3 in zip(cur_past_t.items(),cur_pres_t.items(),cur_fut_t.items()):
  2671. self.cur_past[x1[0]] = TSS.time_series\
  2672. (x1[1],start_date=TSS.Date(freq=self.cur_past[x1[0]].start_date.freqstr,
  2673. year=self.cur_past[x1[0]].start_date.year,
  2674. quarter=self.cur_past[x1[0]].start_date.quarter),
  2675. freq=self.cur_past[x1[0]].start_date.freqstr)
  2676. self.cur_pres[x1[0]] = TSS.time_series\
  2677. (x2[1],start_date=TSS.Date(freq=self.cur_pres[x1[0]].start_date.freqstr,
  2678. year=self.cur_pres[x1[0]].start_date.year,
  2679. quarter=self.cur_pres[x1[0]].start_date.quarter),
  2680. freq=self.cur_pres[x1[0]].start_date.freqstr)
  2681. self.cur_fut[x1[0]] = TSS.time_series\
  2682. (x3[1],start_date=TSS.Date(freq=self.cur_fut[x1[0]].start_date.freqstr,
  2683. year=self.cur_fut[x1[0]].start_date.year,
  2684. quarter=self.cur_fut[x1[0]].start_date.quarter),
  2685. freq=self.cur_fut[x1[0]].start_date.freqstr)