PageRenderTime 84ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/TransitionMatrix.py

https://bitbucket.org/jiefujie/hw2_2_9815
Python | 48 lines | 42 code | 2 blank | 4 comment | 0 complexity | aad1d0c3f59ddd20436f0626df17b3d8 MD5 | raw file
  1. import pandas
  2. import numpy
  3. '''
  4. Interprets a csv file with symmetric labels and data as a transition probability matrix
  5. '''
  6. class TransitionMatrix:
  7. def __init__(self,filename):
  8. '''
  9. Initializes TransitionMatrix object from data in 'filename' csv file
  10. Stores as DataFrame
  11. Copies labels of transition states
  12. '''
  13. self.transitions = pandas.read_csv(filename, index_col = 0)
  14. self.states = self.transitions.index
  15. def get_dataframe(self):
  16. '''
  17. Returns data as a DataFrame object with appropriate labels
  18. '''
  19. return self.transitions
  20. def get_matrix(self):
  21. '''
  22. Returns data as a numpy matrix (no labels)
  23. '''
  24. return numpy.matrix(self.transitions)
  25. def future_transition(self, years):
  26. '''
  27. Calculates the transition matrix corresponding to the cumulative probability
  28. of transition from/to each state with a specified number of years
  29. Does this by finding the nth power of the matrix
  30. '''
  31. matrix = self.get_matrix()
  32. for i in range(years - 1):
  33. matrix = matrix*self.get_matrix()
  34. matrix = pandas.DataFrame(matrix, index = self.states, columns = self.states)
  35. return matrix
  36. def future_transition_to(self, label, years):
  37. '''
  38. Calculates a future transition matrix and pulls the column corresponding to
  39. the label; useful for calculating default probabilities
  40. '''
  41. matrix = self.future_transition(years)
  42. return matrix[label]