jmarkov 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
jmarkov/__init__.py ADDED
File without changes
jmarkov/ctmc.py ADDED
@@ -0,0 +1,199 @@
1
+ import numpy as np
2
+ from scipy import linalg
3
+ from scipy import sparse
4
+ from .markov_chain import markov_chain
5
+
6
+ class ctmc(markov_chain):
7
+ """
8
+ Implements a finite continuous-time Markov chain (CTMC)
9
+
10
+ The chain is defined by its number of states, states, and a
11
+ generator matrix. The class provides methods to compute both
12
+ stationary and transient metrics, as well as to check the
13
+ chain properties (ergodicity).
14
+ """
15
+
16
+ # number of states in string array form
17
+ n_states:int=1
18
+
19
+ # states in string array form
20
+ states:np.array = np.array([1])
21
+
22
+ # generator matrix as 2d numpy array
23
+ generator:np.array
24
+
25
+ # empty initializer
26
+ # chain with a single state
27
+ def __init__(self):
28
+ self.n_states = 1
29
+ self.generator = np.array([0])
30
+
31
+ # initializer with only the number of states
32
+ def __init__(self,n:int):
33
+ self.n_states = n
34
+ self.generator = np.zeros((n,n), dtype=float)
35
+
36
+ # initializer with a generator matrix
37
+ def __init__(self,generator:np.array):
38
+ """
39
+ Creates a continuous-time Markov chain from its generator matrix
40
+ """
41
+ if not self._check_generator_matrix(generator):#Lets check if transition matrix is logical (i.e the rows sum 0)
42
+ raise ValueError("the rows of generator matrix do not sum 0 or the diagonal has non negative values")
43
+ self.n_states=generator.shape[0]
44
+ self.generator = generator
45
+
46
+
47
+ def _check_generator_matrix(self,M:np.ndarray):
48
+ """
49
+ Checks that a matrix is a Markov chain generator
50
+
51
+ Checks that all row sums are equal to zero, diagonal entries are non-positive, and
52
+ non-diagonal entries are non-negative
53
+ """
54
+ #
55
+ vector = np.isclose(np.sum(M, axis = 1),0,1e-5) == True
56
+ # Check if a given transition matrix has all diagonal elements non positive
57
+ if vector.all() and np.all(np.diag(M)<0):
58
+ return True
59
+ else:
60
+ return False
61
+
62
+
63
+ def steady_state(self) -> np.ndarray:
64
+ """
65
+ Computes the steady state distribution of the continuous-time Markov chain
66
+
67
+ Computes the steady state probability distribution by replacing one of the
68
+ matrix equations with a normalizing equation that ensures the result is a
69
+ probability distribution.
70
+
71
+ Returns the stationary probability distribution in array form
72
+ """
73
+
74
+ #
75
+ if self.generator.any():
76
+ # sets A to be Q and replace first column with ones for the normalizing equation
77
+ A = self.generator.copy()
78
+ A[:, 0] = 1
79
+ # sets b as the right hand vector with a 1 for the normalizing equation
80
+ b = np.zeros(self.n_states, dtype=float)
81
+ b[0] = 1
82
+ # solves transposed system as pi is a row vector
83
+ res = linalg.solve(A,b,transposed=True)
84
+ return res
85
+ else:
86
+ print("Empty generator matrix")
87
+ return 0
88
+
89
+
90
+ def transient_probabilities(self,t:float,alpha:np.ndarray) -> np.ndarray:
91
+ """
92
+ Computes the transient distribution at time t with initial state alpha
93
+
94
+ Computes alpha*exp(Q*t)*ones to obtain the probability distribution
95
+ at time t given the initial probability distribution alpha
96
+ """
97
+ shape=alpha.shape#lets get the shape of alpha vector
98
+ if shape[0]!=self.n_states:
99
+ raise ValueError("The dimensions of alpha vector are incorrect. It must be a vector 1xn_states")
100
+ P=linalg.expm(self.generator*t)#exponentiate the diferential generator following the method of Mohy et al (https://eprints.maths.manchester.ac.uk/1300/1/alhi09a.pdf)
101
+ probs=alpha@P
102
+ return probs
103
+
104
+
105
+ def first_passage_time(self, target:str):
106
+ """
107
+ Computes the expected first passage time to a target state from a start state.
108
+
109
+ This method calculates the expected number of steps required for the Markov chain to reach
110
+ the specified target state from the start state by creating a sub-matrix of the generator matrix with the target removed.
111
+
112
+ Returns the expected steps to reach the target state from any start state (except target) in array form
113
+ """
114
+ #The transition matrix and the number of states are brought
115
+ e=self.n_states
116
+ q=self.generator.copy()
117
+
118
+ # Matrix of ones with n-1 rows is created
119
+ u=np.full([e-1,1],1)
120
+
121
+ #The column and row corresponding to the target state are eliminated from the transition matrix
122
+ m=np.delete(q,target, axis=0)
123
+ m=np.delete(m,target, axis=1)
124
+
125
+
126
+ t=np.matmul(np.linalg.inv(-m),u)
127
+ return t
128
+
129
+ def occupation_time(self,T,Epsilon=0.00001):
130
+ n=self.n_states
131
+ m=self.generator.copy()
132
+ def P_from_R(n,m):
133
+ # Inicializamos el valor máximo con el primer elemento de la diagonal
134
+ Vector_ri=np.diagonal(m)
135
+ #Hallamos la r como el máximo de las r_i
136
+ r=max(-Vector_ri)
137
+ return r
138
+ def creacion_P(n,m):
139
+ r= P_from_R(n,m)
140
+ #Hallamos la matriz P^
141
+ h=np.zeros((n,n))
142
+ for i in range(n):
143
+ for j in range(n):
144
+ if i==j:
145
+ h[i][j]=1+(m[i][j]/r)
146
+ else:
147
+ h[i][j]=m[i][j]/r
148
+ return h
149
+ r=P_from_R(n,m)
150
+ P=creacion_P(n,m)
151
+ i=np.identity(n)
152
+ A=P
153
+ k=0
154
+ yek=np.exp(-r*T)
155
+ ygk=1-yek
156
+ suma=ygk
157
+ B=ygk*i
158
+ while suma/r < T-Epsilon:
159
+ k=k+1
160
+ yek=yek*(r*T)/k
161
+ ygk=ygk-yek
162
+ B=B+ygk*A
163
+ A=A@P
164
+ suma=suma+ygk
165
+ return (B/r)
166
+
167
+
168
+ def is_irreducible(self):
169
+ """
170
+ Checks if the given continous-time Markov Chain is irreducible.
171
+
172
+ This method determines if the continous-time Markov Chain is irreducible by checking if, starting in
173
+ any state, it is possible to reach any other state in a sequence of transitions.
174
+
175
+ Returns a boolean
176
+ """
177
+ # the finite case:
178
+
179
+ # We bring the generator matrix and replace all the diagonal elements for 0
180
+ Q = np.copy(self.generator)
181
+ np.fill_diagonal(Q,0)
182
+ # We check if all the components in the chain are strongly connected
183
+ if sparse.csgraph.connected_components(Q, directed=True,connection='strong',return_labels=False)==1:
184
+ return True
185
+ else:
186
+ return False
187
+
188
+ def is_ergodic(self):
189
+ """
190
+ Checks if a given continous-time Markov Chain is ergodic.
191
+
192
+ Given that a finite continous-time Markov Chain is ergodic if it is irreducible, this
193
+ method checks if it is irreducible to determine if the provided chain is ergodic or not.
194
+ """
195
+ # We check if the chain is irreducible
196
+ if self.is_irreducible()==True:
197
+ return True
198
+ else:
199
+ return False
jmarkov/dtmc.py ADDED
@@ -0,0 +1,216 @@
1
+ import numpy as np
2
+ from scipy import linalg
3
+ from scipy import sparse
4
+ from .markov_chain import markov_chain
5
+ import math
6
+
7
+ class dtmc(markov_chain):
8
+ """
9
+ Implements a finite discrete-time Markov chain (CTMC)
10
+
11
+ The chain is defined by its number of states, states, and a
12
+ transition matrix. The class provides methods to compute both
13
+ stationary and transient metrics, as well as to check the
14
+ chain properties (aperiodicity and ergodicity).
15
+ """
16
+
17
+ # number of states in string array form
18
+ n_states:int=1
19
+
20
+ # states in string array form
21
+ states:np.array = np.array([1])
22
+
23
+ # transition matrix as 2d numpy array
24
+ transition_matrix:np.array
25
+
26
+ # empty initializer
27
+ # chain with a single state
28
+ def __init__(self):
29
+ """
30
+ Creates a continuous-time Markov chain from its transition matrix
31
+ """
32
+ self.n_states = 1
33
+ self.transition_matrix = np.array([1])
34
+
35
+ # initializer with only the number of states
36
+ def __init__(self,n:int):
37
+ self.n_states = n
38
+ self.transition_matrix = np.eye(n, dtype=float)
39
+
40
+ # initializer with a transition matrix
41
+ def __init__(self,transition_matrix:np.array):
42
+ if not self._check_transition_matrix(transition_matrix):#Lets check if transition matrix is logical (i.e the rows sum 1)
43
+ raise ValueError("the rows of transition matrix do not sum 1 or has non positive values")
44
+ self.n_states=transition_matrix.shape[0]
45
+ self.transition_matrix = transition_matrix
46
+
47
+ def _check_transition_matrix(self, M:np.array):
48
+ """
49
+ Checks that a matrix is a Markov chain transition matrix
50
+
51
+ Checks that all entries are non-negative and all row sums are equal to one
52
+ """
53
+ #Check if a given transition matrix has the condition that for every row the sum of all elements is equal to 1
54
+ #Check if a given transition matrix has the condition that every element of the matrix is between 0 and 1
55
+ if np.all(np.isclose(np.sum(M,axis=1),1,1e-5)) and np.all((M>=0) & (M<=1)):
56
+ return True
57
+ else:
58
+ return False
59
+
60
+
61
+ def steady_state(self) -> np.ndarray:
62
+ """
63
+ Computes the steady state distribution of the discrete-time Markov chain
64
+
65
+ Computes the steady state probability distribution by replacing one of the
66
+ matrix equations with a normalizing equation that ensures the result is a
67
+ probability distribution.
68
+
69
+ Returns the stationary probability distribution in array form
70
+ """
71
+ # computes the steady state distribution
72
+ if self.transition_matrix.any():
73
+ # sets A to be I-P and replace first column with ones for the normalizing equation
74
+ A = self.transition_matrix - np.eye(self.n_states, dtype=float)
75
+ A[:, 0] = 1
76
+ # sets b as the right hand vector with a 1 for the normalizing equation
77
+ b = np.zeros(self.n_states, dtype=float)
78
+ b[0] = 1
79
+ # solves transposed system as pi is a row vector
80
+ res = linalg.solve(A,b,transposed=True)
81
+ return res
82
+ else:
83
+ print("Empty transition matrix")
84
+ return 0
85
+
86
+
87
+ def transient_probabilities(self,n,alpha):
88
+ """
89
+ Computes the transient distribution at transition n with initial state alpha
90
+
91
+ Computes alpha*(P^n)*ones to obtain the probability distribution
92
+ at time/transition n given the initial probability distribution alpha
93
+ """
94
+
95
+ #First, lets verify n is integer
96
+ if not isinstance(n,int):
97
+ raise ValueError("The number of transitions n must be integer")
98
+ #Now lets verify the dimensions of the vector alpha:
99
+ try:
100
+ shape=alpha.shape
101
+ except:
102
+ print("alpha vector must be a numpy array")
103
+ return None
104
+ if shape[0]!=self.n_states:
105
+ raise ValueError("The dimensions of alpha vector are incorrect. It must be a vector 1xn_states")
106
+
107
+ #Computes transient_matrix**n
108
+ matrix_n=np.linalg.matrix_power(self.transition_matrix,n)
109
+ vector=alpha@matrix_n
110
+ return vector
111
+
112
+
113
+ def first_passage_time(self, target:str):
114
+ """
115
+ Computes the expected first passage time to a target state from a start state.
116
+
117
+ This method calculates the expected number of steps required for the Markov chain to reach
118
+ the specified target state from the start state by creating a sub-matrix of the transition matrix with the target removed.
119
+
120
+ Returns the expected steps to reach the target state from any start state (except target) in array form
121
+ """
122
+ #The transition matrix and the number of states are brought
123
+ n=self.n_states
124
+ M=self.transition_matrix.copy()
125
+ # The identity matrix is created with size n-1 states
126
+ i=np.identity(n-1)
127
+ # Matrix of ones with n-1 rows is created
128
+ u=np.full([n-1,1],1)
129
+ # The column and row corresponding to the target state are eliminated from the transition matrix
130
+ p=np.delete(M,target, axis=0)
131
+ p=np.delete(p,target, axis=1)
132
+
133
+ t=np.matmul(np.linalg.inv(i-p),u)
134
+ return t
135
+
136
+ def occupation_time(self, n:int):
137
+ """
138
+ Computes the expected occupation time in n steps.
139
+
140
+ This method calculates the expected time that the discrete-time Markov chain will remain in each state, from all starting states.
141
+
142
+
143
+ Returns the occupation matrix in array form
144
+ """
145
+ # Create an identity matrix with the same shape of transition matrix
146
+ occupation=np.eye(self.transition_matrix.shape[0],self.transition_matrix.shape[1])
147
+ # Iterate for each step
148
+ for i in range(1,n+1):
149
+ # Calculate the occupation time for each step, and update the occupation matrix
150
+ occupation+=np.linalg.matrix_power(self.transition_matrix,i)
151
+ return occupation
152
+
153
+ def period(self):
154
+ """
155
+ Computes the period of a discrete-time Markov Chain.
156
+
157
+ This method calculates the period of a discrete-time Markov Chain by iterating a total of N steps, where N represents
158
+ the number of states that the chain has. In each k-th iteration, the chain is elevated to the k-th power to compute the
159
+ transient probabilities in the k-th step. If one of the elementsin in the diagonal of the resulting matrix is greater than 0,
160
+ the chain can potentially have a period k. The period of the matrix will be the Greatest Common Divisor (GCD) between the
161
+ potential new period of the matrix in the k-th iteration and the current GCD before the k-th iteration.
162
+
163
+ Returns the period of the chain as an int
164
+ """
165
+
166
+ #Initializes the transition matrix and the greatest common divisor for the periodicity calculations
167
+ P_k = self.transition_matrix
168
+ gcd = 0
169
+
170
+ #Loop to elevate the transition matrix to the k th power and evaluate its periodicity:
171
+ for k in range(2, (self.n_states)+1):
172
+ P_k = np.dot(self.transition_matrix, P_k)
173
+ #If the transition matrix to the k-th power has a non-zero element in its diagonal, the chain could have a period k:
174
+ if np.any(np.diagonal(P_k) != 0):
175
+ #GCD between the current GCD for the period of the matrix and the potential new GCD
176
+ gcd = math.gcd(gcd, k)
177
+ #If the GCD is 1, there is no need to keep looking for the period, the chain is aperiodic:
178
+ if gcd == 1:
179
+ break
180
+ return gcd
181
+
182
+ def is_irreducible(self):
183
+ """
184
+ Checks if the given discrete-time Markov Chain is irreducible.
185
+
186
+ This method determines if the discrete-time Markov Chain is irreducible by checking if, starting in
187
+ any state, it is possible to reach any other state in a sequence of transitions.
188
+
189
+ Returns a boolean
190
+ """
191
+ # Brings a copy of the transition matrix
192
+ P = np.copy(self.transition_matrix)
193
+ # Checks if all the states in the Markov chain are strongly connected
194
+ if sparse.csgraph.connected_components(P, directed=True,connection='strong',return_labels=False)==1:
195
+ return True
196
+ else:
197
+ return False
198
+
199
+ def is_ergodic(self):
200
+ """
201
+ Checks if a given discrete-time Markov Chain is ergodic.
202
+
203
+ Given that a finite discrete-time Markov Chain is ergodic if it is aperiodic and irreducible, this
204
+ method checks if both conditions are met to determine if the provided chain is ergodic or not.
205
+
206
+ Returns a boolean
207
+ """
208
+ # Checks if the chain is irreducible and if it has a period of 1
209
+ if self.period() == 1 & self.is_irreducible() == True:
210
+ return True
211
+ else:
212
+ return False
213
+
214
+
215
+
216
+
@@ -0,0 +1,36 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+ class markov_chain(ABC):
4
+
5
+ @property
6
+ @abstractmethod
7
+ def n_states(self):
8
+ # number of states
9
+ pass
10
+
11
+ @property
12
+ @abstractmethod
13
+ def states(self):
14
+ # markov chain states
15
+ pass
16
+
17
+ @abstractmethod
18
+ def steady_state(self):
19
+ # computes the steady state distribution
20
+ pass
21
+
22
+ @abstractmethod
23
+ def first_passage_time(self, target:str):
24
+ # computes the expected first passage time to target state
25
+ pass
26
+
27
+ @abstractmethod
28
+ def occupation_time(self, nsteps:int):
29
+ # computes the expected occupation time matrix in nsteps steps
30
+ pass
31
+
32
+ @abstractmethod
33
+ def is_ergodic(self):
34
+ # determines id the chain is ergodic or not
35
+ pass
36
+
File without changes
jmarkov/mdp/dtmdp.py ADDED
@@ -0,0 +1,219 @@
1
+ import numpy as np
2
+ from typing import Dict
3
+ import sys
4
+ import os.path
5
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..','..')))
6
+ from jmarkov.dtmc import dtmc
7
+
8
+ class dtmdp():
9
+ """
10
+ Implements a Markov decision process (MDP)
11
+
12
+ The process is defined by its number of states, states, number of actions, actions,
13
+ the immediate returns of implementing each action and a transition matrix for each action.
14
+ The class provides methods to solve MDPs and to compute the expected value of the optimal policy.
15
+ """
16
+ # number of states in string array form
17
+ n_states:int=1
18
+ # states in string array form
19
+ states:np.array = np.array([1])
20
+ # number of actions
21
+ n_actions:int=1
22
+ # actions in array form
23
+ actions:np.array = np.array([1])
24
+ # transition matrix as dict of numpy arrays
25
+ transition_matrices:Dict[str, np.array]
26
+ # immediate return matrix as 2d numpy array
27
+ immediate_returns:np.array = np.array([1])
28
+ # discount factor as int
29
+ discount_factor:int = 0.8
30
+ # initializer with a transition matrix, immediate returns and discount factor
31
+ def __init__(self,states:np.array, actions: np.array, transition_matrices:Dict, immediate_returns: np.array,discount_factor:int):
32
+ """
33
+ Creates a markov decision process from its transition matrices, immediate returns and discount factor
34
+ """
35
+ if not self._check_transition_matrices(transition_matrices):#Lets check if transition matrix is logical (i.e the rows sum 1)
36
+ raise ValueError("the rows of transition matrices do not sum 1 or have non positive values")
37
+ if not self._check_immediate_returns(immediate_returns,transition_matrices): # Lets check if immediate returns are consistent
38
+ raise ValueError("the dimensions of the immediate returns are not coherent")
39
+ if not self._check_discount_factor(discount_factor): # Lets check if discount factor is logical
40
+ raise ValueError("discount factor should be a number between 0 and 1")
41
+ self.n_actions = len(transition_matrices)
42
+ self.n_states=len(transition_matrices[next(iter(transition_matrices))])
43
+ self.transition_matrices = transition_matrices
44
+ self.immediate_returns = immediate_returns
45
+ self.discount_factor = discount_factor
46
+ self.actions = actions
47
+ self.states = states
48
+
49
+ def _check_transition_matrices(self, M:Dict):
50
+ """
51
+ Checks that all matrices are stochastic
52
+
53
+ Checks that all row sums are equal to one and all elements are non negative
54
+ """
55
+ # determines if the transition matrices are logical
56
+ # i.e: if the sum of the rows equals to 1 (is an stochastic matrix)
57
+ # and if all of the elements are positive
58
+ if all(np.all((np.array(value) >= 0) & (np.array(value) <= 1)) for value in M.values()) and np.all(np.isclose(np.sum(list(M.values()), axis=2), 1, atol=1e-5)):
59
+ return True
60
+ else:
61
+ return False
62
+
63
+ def _check_immediate_returns(self,R:np.array, M:Dict):
64
+ """
65
+ Checks that the immediate returns are valid and dimensionally-coherent
66
+
67
+ Checks that immediate return array has dimensions length of states x length of actions
68
+ """
69
+ # checks if the dimensions of immediate returns are coherent
70
+ # expected: len(S) x len(actions)
71
+ if R.shape == (len(list(M.values())[0]),len(M)):
72
+ return True
73
+
74
+ def _check_discount_factor(self,beta:int):
75
+ """
76
+ Checks that the discount factor is valid
77
+
78
+ Checks that discount factor is a number equal to or greater than 0 and less than 1
79
+ """
80
+ # checks if the discount factor is a number between 0 and 1
81
+ if beta >= 0 and beta < 1:
82
+ return True
83
+ else:
84
+ return False
85
+
86
+ def solve(self, tolerance, minimize = False, method = "value_iteration"):
87
+ """
88
+ Solves MDP's with defined method
89
+
90
+ Returns the expected value of following the optimal policy at each state and the optimal policy for each state
91
+ """
92
+ S = self.states
93
+ A = self.actions
94
+ M = self.transition_matrices
95
+ R = self.immediate_returns
96
+ beta = self.discount_factor
97
+
98
+ # if the sense of the search is minimize, change the values of the immediate returns
99
+ # so that we maximize minimums
100
+ if minimize == True:
101
+ R = -1*R
102
+
103
+ if method == "value_iteration":
104
+ result = value_iteration(S, A, M, R, beta, tolerance)
105
+ V = result[0]
106
+ optimal_policy = result[1]
107
+ elif method == "policy_iteration":
108
+ result = policy_iteration(S, A, M, R, beta, tolerance)
109
+ V = result[0]
110
+ optimal_policy = result[1]
111
+
112
+ if minimize == True:
113
+ V = -1 * V
114
+ # return the optimal policy
115
+ return V, optimal_policy
116
+
117
+ def policy_transition_matrix(self, policy):
118
+ """
119
+ Calculates the expected value of a policy according
120
+
121
+ Returns the transition matrix for following the optimal policy
122
+ """
123
+ # gets the transition matrix for the optimal policy
124
+ S = self.states
125
+ M = self.transition_matrices
126
+ optimal_transition_matrix = []
127
+ for i in range(0, len(S)):
128
+ optimal_transition_matrix.append(M[policy[S[i]]][i])
129
+ optimal_transition_matrix = np.array(optimal_transition_matrix)
130
+ return optimal_transition_matrix
131
+
132
+ def expected_policy_value(self, value_function, policy):
133
+ """
134
+ Calculates the expected value of a policy according to the steady state probability of being in each state
135
+
136
+ Returns the expected value of following the optimal policy
137
+ """
138
+ # gets the transition matrix for the optimal policy
139
+ optimal_transition_matrix = self.policy_transition_matrix(policy)
140
+ # creates the dtmc object
141
+ mc = dtmc(optimal_transition_matrix)
142
+ expected_value = sum(mc.steady_state()*value_function)
143
+ return expected_value
144
+
145
+ def value_iteration(S, A, M, R, beta, tolerance):
146
+ # initialize value functions
147
+ V = np.zeros(len(S))
148
+ # initialize optimal policy
149
+ optimal_policy = {S[i]: A[0] for i in range(0, len(S))}
150
+ # iterate while there is no improvement
151
+ while True:
152
+ # save values from previous iteration
153
+ oldV = V.copy()
154
+ # iterate through states
155
+ for i in range(0, len(S)):
156
+ # initialize Q -> value-action function
157
+ Q = {}
158
+ # iterate through actions
159
+ for a in range(0,len(A)):
160
+ # evaluate the new value function
161
+ Q[A[a]] = R[i, a] + beta*sum(M[A[a]][i,j]*oldV[j] for j in range(0, len(S)))
162
+ # update the new value function for each state
163
+ V[i] = max(Q.values())
164
+ # update the action for each state
165
+ optimal_policy[S[i]] = max(Q, key = Q.get)
166
+
167
+ # if there is no improvement break the cycle
168
+ if np.allclose(oldV, V, tolerance):
169
+ break
170
+ return V, optimal_policy
171
+
172
+ def policy_improvement(V, S, A, M, R, beta):
173
+ # initialize optimal policy
174
+ optimal_policy = {S[i]: A[0] for i in range(0, len(S))}
175
+ # iterate through states
176
+ for i in range(0, len(S)):
177
+ # initialize Q -> value-action function
178
+ Q = {}
179
+ # iterate through actions
180
+ for a in range(0, len(A)):
181
+ # evaluate the new value function
182
+ Q[A[a]] = R[i,a] + beta*sum(M[A[a]][i,j]*V[j] for j in range(0, len(S)))
183
+ # update the action for each state
184
+ optimal_policy[S[i]] = max(Q, key = Q.get)
185
+ return optimal_policy
186
+
187
+ def policy_evaluation(policy, S, A, M, R, beta, tolerance):
188
+ # initialize value functions
189
+ V = np.zeros(len(S))
190
+ # iterate while there is improvement
191
+ while True:
192
+ # save old values of value functions
193
+ oldV = V.copy()
194
+ # iterate through states
195
+ for i in range(0,len(S)):
196
+ # save current policy
197
+ a = np.where(A == policy[S[i]])[0][0]
198
+ # evaluate the current policy for each state
199
+ V[i] = R[i,a] + beta*sum(M[A[a]][i,j]*V[j] for j in range(0,len(S)))
200
+ # if there is no improvement break the cycle
201
+ if np.allclose(oldV, V, tolerance):
202
+ break
203
+ return V
204
+
205
+ def policy_iteration(S, A, M, R, beta, tolerance):
206
+ # initialize optimal policy
207
+ optimal_policy = {S[i]: A[0] for i in range(0, len(S))}
208
+ # iterate while there is improvement
209
+ while True:
210
+ # save values of current policy
211
+ old_policy = optimal_policy.copy()
212
+ # evaluate current policy
213
+ V = policy_evaluation(optimal_policy, S, A, M, R, beta, tolerance)
214
+ # improve current policy
215
+ optimal_policy = policy_improvement(V, S, A, M, R, beta)
216
+ # if old policy and new policy are the same (there is no improvement) break cycle
217
+ if all(old_policy[S[i]] == optimal_policy[S[i]] for i in range(0, len(S))):
218
+ break
219
+ return V, optimal_policy
File without changes
jmarkov/phase/ctph.py ADDED
@@ -0,0 +1,59 @@
1
+ import numpy as np
2
+ from scipy import linalg
3
+ from scipy import sparse
4
+
5
+ class ctph():
6
+
7
+ # number of phases
8
+ n_phases:int=1
9
+
10
+ # subgenerator matrix as 2d numpy array
11
+ T:np.array
12
+
13
+ # initial phase vector as 1d numpy array
14
+ alpha:np.array
15
+
16
+ # empty initializer
17
+ # chain with a single state
18
+ def __init__(self):
19
+ self.n_phases = 1
20
+ self.T = np.array([-1])
21
+ self.alpha = np.array([1])
22
+
23
+ # initializer with only the number of states
24
+ def __init__(self,n:int):
25
+ self.n_phases = n
26
+ self.generator = -1*np.eye(n, dtype=float)
27
+ self.alpha = np.zeros(n, dtype=float)
28
+ self.alpha[0] = 1
29
+
30
+ # initializer with both alpha and T
31
+ def __init__(self, alpha:np.array, T:np.array):
32
+ if not self._check_sub_generator_matrix(T): #Lets check if transition matrix is logical (i.e the rows sum 0)
33
+ raise ValueError("the rows of transition matrix do not sum 0 or the diagonal has non negative values")
34
+ self.n_phases=T.shape[0]
35
+ self.T = T
36
+ shape = alpha.shape
37
+ if shape[0]!=self.n_phases:
38
+ raise ValueError("The dimensions of alpha vector are incorrect. Its length must coincide with the size of T")
39
+ self.alpha = alpha
40
+
41
+ def _check_sub_generator_matrix(self, M:np.ndarray):
42
+ #Check if a given rate matrix has the condition that every row sum <= 0, with at least one < 0
43
+ check1 = np.max(np.sum(M, axis = 1)) <= 0 and np.min(np.sum(M, axis = 1)) < 0
44
+ # Check if a given transition matrix has all diagonal elements non positive
45
+ if check1 and np.all(np.diag(M)<0):
46
+ return True
47
+ else:
48
+ return False
49
+
50
+ def pdf(self,t:float) -> np.float64:
51
+ P=linalg.expm(self.T*t) #exponentiate the diferential generator following the method of Mohy et al (https://eprints.maths.manchester.ac.uk/1300/1/alhi09a.pdf)
52
+ probs=self.alpha@P
53
+ return sum(probs)
54
+
55
+
56
+ def expected_value(self):
57
+ # Compute the expected value as alpha*inv(T)*one
58
+ return np.sum(self.alpha@np.linalg.inv(-self.T))
59
+
jmarkov/phase/dtph.py ADDED
@@ -0,0 +1,57 @@
1
+ import numpy as np
2
+ from scipy import linalg
3
+ from scipy import sparse
4
+
5
+ class dtph():
6
+
7
+ # number of phases
8
+ n_phases:int=1
9
+
10
+ # substochastic matrix as 2d numpy array
11
+ T:np.array
12
+
13
+ # initial phase vector as 1d numpy array
14
+ alpha:np.array
15
+
16
+ # empty initializer
17
+ # chain with a single state
18
+ def __init__(self):
19
+ self.n_phases = 1
20
+ self.T = np.array([0.8])
21
+ self.alpha = np.array([1])
22
+
23
+ # initializer with only the number of states
24
+ def __init__(self,n:int):
25
+ self.n_phases = n
26
+ self.generator = np.zeros((n,n), dtype=float)
27
+ self.alpha = np.zeros(n, dtype=float)
28
+ self.alpha[0] = 1
29
+
30
+ # initializer with both alpha and T
31
+ def __init__(self, alpha:np.array, T:np.array):
32
+ if not self._check_sub_stochastic_matrix(T): #Lets check if transition matrix is logical (i.e the rows sum <=1)
33
+ raise ValueError("the rows of transition matrix do not sum <= 1")
34
+ self.n_phases=T.shape[0]
35
+ self.T = T
36
+ shape = alpha.shape
37
+ if shape[0]!=self.n_phases:
38
+ raise ValueError("The dimensions of alpha vector are incorrect. Its length must coincide with the size of T")
39
+ self.alpha = alpha
40
+
41
+ def _check_sub_stochastic_matrix(self, M:np.ndarray):
42
+ #Check if a given rate matrix has the condition that every row sum <= 0, with at least one < 0
43
+ if np.max(np.sum(M, axis = 1)) <= 1 and np.min(np.sum(M, axis = 1)) < 1:
44
+ return True
45
+ else:
46
+ return False
47
+
48
+ def pmf(self,n:int) -> np.float64:
49
+ P=np.linalg.matrix_power(self.T,n)
50
+ probs=self.alpha@P
51
+ return sum(probs)
52
+
53
+
54
+ def expected_value(self):
55
+ # Compute the expected value as alpha*inv(I - T)*one
56
+ return np.sum(self.alpha@(np.eye(self.n_phases) - np.linalg.inv(-self.T)))
57
+
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.3
2
+ Name: jmarkov
3
+ Version: 0.0.1
4
+ Summary: A python package for Markov chain modeling
5
+ Project-URL: Homepage, https://github.com/copa-uniandes/jmarkov
6
+ Project-URL: Issues, https://github.com/copa-uniandes/jmarkov/issues
7
+ Author-email: Juan F Perez <juanfernando.perez@gmail.com>
8
+ License-File: LICENSE
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.8
13
+ Requires-Dist: numpy
14
+ Requires-Dist: scipy
15
+ Requires-Dist: typing
16
+ Description-Content-Type: text/markdown
17
+
18
+ # jmarkov
19
+ jMarkov is a library to simplify the modeling of systems with Markov chains.
@@ -0,0 +1,13 @@
1
+ jmarkov/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ jmarkov/ctmc.py,sha256=JV1G1qBWNecnqrZXrplQrPZ1BT27fu27u07bt-V5EF0,7283
3
+ jmarkov/dtmc.py,sha256=6H-lfaelR5j9cbIOpVgCHEMGXUjT_n12z3Q9tGsbjUI,9180
4
+ jmarkov/markov_chain.py,sha256=IdJxqfudti4lceWfpRR-r3vy0AbbsGNzjP662HPCF10,816
5
+ jmarkov/mdp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ jmarkov/mdp/dtmdp.py,sha256=0W31b8ebqE75SqjnLawUHgBLRfzLhAfh4KAj6IBpUEw,9373
7
+ jmarkov/phase/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ jmarkov/phase/ctph.py,sha256=29vKGGaFPBVj7DndO5CGFBna_2JWOzyTtfjy2kWzF-w,2159
9
+ jmarkov/phase/dtph.py,sha256=m7YQGpOarxYYFEYQl4XRy65FXY5n1mhvBv8A07ncZb4,1899
10
+ jmarkov-0.0.1.dist-info/METADATA,sha256=JuyPvbb7Qxp3ouGr4D668KIBBsbhtWi0E2oddYbTHPs,677
11
+ jmarkov-0.0.1.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
12
+ jmarkov-0.0.1.dist-info/licenses/LICENSE,sha256=bDkGfTup1HnHpyVtgn2N5sZUHHhux3olwawM3_ijDiM,14474
13
+ jmarkov-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.25.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,277 @@
1
+ Eclipse Public License - v 2.0
2
+
3
+ THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
4
+ PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION
5
+ OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
6
+
7
+ 1. DEFINITIONS
8
+
9
+ "Contribution" means:
10
+
11
+ a) in the case of the initial Contributor, the initial content
12
+ Distributed under this Agreement, and
13
+
14
+ b) in the case of each subsequent Contributor:
15
+ i) changes to the Program, and
16
+ ii) additions to the Program;
17
+ where such changes and/or additions to the Program originate from
18
+ and are Distributed by that particular Contributor. A Contribution
19
+ "originates" from a Contributor if it was added to the Program by
20
+ such Contributor itself or anyone acting on such Contributor's behalf.
21
+ Contributions do not include changes or additions to the Program that
22
+ are not Modified Works.
23
+
24
+ "Contributor" means any person or entity that Distributes the Program.
25
+
26
+ "Licensed Patents" mean patent claims licensable by a Contributor which
27
+ are necessarily infringed by the use or sale of its Contribution alone
28
+ or when combined with the Program.
29
+
30
+ "Program" means the Contributions Distributed in accordance with this
31
+ Agreement.
32
+
33
+ "Recipient" means anyone who receives the Program under this Agreement
34
+ or any Secondary License (as applicable), including Contributors.
35
+
36
+ "Derivative Works" shall mean any work, whether in Source Code or other
37
+ form, that is based on (or derived from) the Program and for which the
38
+ editorial revisions, annotations, elaborations, or other modifications
39
+ represent, as a whole, an original work of authorship.
40
+
41
+ "Modified Works" shall mean any work in Source Code or other form that
42
+ results from an addition to, deletion from, or modification of the
43
+ contents of the Program, including, for purposes of clarity any new file
44
+ in Source Code form that contains any contents of the Program. Modified
45
+ Works shall not include works that contain only declarations,
46
+ interfaces, types, classes, structures, or files of the Program solely
47
+ in each case in order to link to, bind by name, or subclass the Program
48
+ or Modified Works thereof.
49
+
50
+ "Distribute" means the acts of a) distributing or b) making available
51
+ in any manner that enables the transfer of a copy.
52
+
53
+ "Source Code" means the form of a Program preferred for making
54
+ modifications, including but not limited to software source code,
55
+ documentation source, and configuration files.
56
+
57
+ "Secondary License" means either the GNU General Public License,
58
+ Version 2.0, or any later versions of that license, including any
59
+ exceptions or additional permissions as identified by the initial
60
+ Contributor.
61
+
62
+ 2. GRANT OF RIGHTS
63
+
64
+ a) Subject to the terms of this Agreement, each Contributor hereby
65
+ grants Recipient a non-exclusive, worldwide, royalty-free copyright
66
+ license to reproduce, prepare Derivative Works of, publicly display,
67
+ publicly perform, Distribute and sublicense the Contribution of such
68
+ Contributor, if any, and such Derivative Works.
69
+
70
+ b) Subject to the terms of this Agreement, each Contributor hereby
71
+ grants Recipient a non-exclusive, worldwide, royalty-free patent
72
+ license under Licensed Patents to make, use, sell, offer to sell,
73
+ import and otherwise transfer the Contribution of such Contributor,
74
+ if any, in Source Code or other form. This patent license shall
75
+ apply to the combination of the Contribution and the Program if, at
76
+ the time the Contribution is added by the Contributor, such addition
77
+ of the Contribution causes such combination to be covered by the
78
+ Licensed Patents. The patent license shall not apply to any other
79
+ combinations which include the Contribution. No hardware per se is
80
+ licensed hereunder.
81
+
82
+ c) Recipient understands that although each Contributor grants the
83
+ licenses to its Contributions set forth herein, no assurances are
84
+ provided by any Contributor that the Program does not infringe the
85
+ patent or other intellectual property rights of any other entity.
86
+ Each Contributor disclaims any liability to Recipient for claims
87
+ brought by any other entity based on infringement of intellectual
88
+ property rights or otherwise. As a condition to exercising the
89
+ rights and licenses granted hereunder, each Recipient hereby
90
+ assumes sole responsibility to secure any other intellectual
91
+ property rights needed, if any. For example, if a third party
92
+ patent license is required to allow Recipient to Distribute the
93
+ Program, it is Recipient's responsibility to acquire that license
94
+ before distributing the Program.
95
+
96
+ d) Each Contributor represents that to its knowledge it has
97
+ sufficient copyright rights in its Contribution, if any, to grant
98
+ the copyright license set forth in this Agreement.
99
+
100
+ e) Notwithstanding the terms of any Secondary License, no
101
+ Contributor makes additional grants to any Recipient (other than
102
+ those set forth in this Agreement) as a result of such Recipient's
103
+ receipt of the Program under the terms of a Secondary License
104
+ (if permitted under the terms of Section 3).
105
+
106
+ 3. REQUIREMENTS
107
+
108
+ 3.1 If a Contributor Distributes the Program in any form, then:
109
+
110
+ a) the Program must also be made available as Source Code, in
111
+ accordance with section 3.2, and the Contributor must accompany
112
+ the Program with a statement that the Source Code for the Program
113
+ is available under this Agreement, and informs Recipients how to
114
+ obtain it in a reasonable manner on or through a medium customarily
115
+ used for software exchange; and
116
+
117
+ b) the Contributor may Distribute the Program under a license
118
+ different than this Agreement, provided that such license:
119
+ i) effectively disclaims on behalf of all other Contributors all
120
+ warranties and conditions, express and implied, including
121
+ warranties or conditions of title and non-infringement, and
122
+ implied warranties or conditions of merchantability and fitness
123
+ for a particular purpose;
124
+
125
+ ii) effectively excludes on behalf of all other Contributors all
126
+ liability for damages, including direct, indirect, special,
127
+ incidental and consequential damages, such as lost profits;
128
+
129
+ iii) does not attempt to limit or alter the recipients' rights
130
+ in the Source Code under section 3.2; and
131
+
132
+ iv) requires any subsequent distribution of the Program by any
133
+ party to be under a license that satisfies the requirements
134
+ of this section 3.
135
+
136
+ 3.2 When the Program is Distributed as Source Code:
137
+
138
+ a) it must be made available under this Agreement, or if the
139
+ Program (i) is combined with other material in a separate file or
140
+ files made available under a Secondary License, and (ii) the initial
141
+ Contributor attached to the Source Code the notice described in
142
+ Exhibit A of this Agreement, then the Program may be made available
143
+ under the terms of such Secondary Licenses, and
144
+
145
+ b) a copy of this Agreement must be included with each copy of
146
+ the Program.
147
+
148
+ 3.3 Contributors may not remove or alter any copyright, patent,
149
+ trademark, attribution notices, disclaimers of warranty, or limitations
150
+ of liability ("notices") contained within the Program from any copy of
151
+ the Program which they Distribute, provided that Contributors may add
152
+ their own appropriate notices.
153
+
154
+ 4. COMMERCIAL DISTRIBUTION
155
+
156
+ Commercial distributors of software may accept certain responsibilities
157
+ with respect to end users, business partners and the like. While this
158
+ license is intended to facilitate the commercial use of the Program,
159
+ the Contributor who includes the Program in a commercial product
160
+ offering should do so in a manner which does not create potential
161
+ liability for other Contributors. Therefore, if a Contributor includes
162
+ the Program in a commercial product offering, such Contributor
163
+ ("Commercial Contributor") hereby agrees to defend and indemnify every
164
+ other Contributor ("Indemnified Contributor") against any losses,
165
+ damages and costs (collectively "Losses") arising from claims, lawsuits
166
+ and other legal actions brought by a third party against the Indemnified
167
+ Contributor to the extent caused by the acts or omissions of such
168
+ Commercial Contributor in connection with its distribution of the Program
169
+ in a commercial product offering. The obligations in this section do not
170
+ apply to any claims or Losses relating to any actual or alleged
171
+ intellectual property infringement. In order to qualify, an Indemnified
172
+ Contributor must: a) promptly notify the Commercial Contributor in
173
+ writing of such claim, and b) allow the Commercial Contributor to control,
174
+ and cooperate with the Commercial Contributor in, the defense and any
175
+ related settlement negotiations. The Indemnified Contributor may
176
+ participate in any such claim at its own expense.
177
+
178
+ For example, a Contributor might include the Program in a commercial
179
+ product offering, Product X. That Contributor is then a Commercial
180
+ Contributor. If that Commercial Contributor then makes performance
181
+ claims, or offers warranties related to Product X, those performance
182
+ claims and warranties are such Commercial Contributor's responsibility
183
+ alone. Under this section, the Commercial Contributor would have to
184
+ defend claims against the other Contributors related to those performance
185
+ claims and warranties, and if a court requires any other Contributor to
186
+ pay any damages as a result, the Commercial Contributor must pay
187
+ those damages.
188
+
189
+ 5. NO WARRANTY
190
+
191
+ EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT
192
+ PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN "AS IS"
193
+ BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR
194
+ IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF
195
+ TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR
196
+ PURPOSE. Each Recipient is solely responsible for determining the
197
+ appropriateness of using and distributing the Program and assumes all
198
+ risks associated with its exercise of rights under this Agreement,
199
+ including but not limited to the risks and costs of program errors,
200
+ compliance with applicable laws, damage to or loss of data, programs
201
+ or equipment, and unavailability or interruption of operations.
202
+
203
+ 6. DISCLAIMER OF LIABILITY
204
+
205
+ EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT
206
+ PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS
207
+ SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
208
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST
209
+ PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
210
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
211
+ ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE
212
+ EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE
213
+ POSSIBILITY OF SUCH DAMAGES.
214
+
215
+ 7. GENERAL
216
+
217
+ If any provision of this Agreement is invalid or unenforceable under
218
+ applicable law, it shall not affect the validity or enforceability of
219
+ the remainder of the terms of this Agreement, and without further
220
+ action by the parties hereto, such provision shall be reformed to the
221
+ minimum extent necessary to make such provision valid and enforceable.
222
+
223
+ If Recipient institutes patent litigation against any entity
224
+ (including a cross-claim or counterclaim in a lawsuit) alleging that the
225
+ Program itself (excluding combinations of the Program with other software
226
+ or hardware) infringes such Recipient's patent(s), then such Recipient's
227
+ rights granted under Section 2(b) shall terminate as of the date such
228
+ litigation is filed.
229
+
230
+ All Recipient's rights under this Agreement shall terminate if it
231
+ fails to comply with any of the material terms or conditions of this
232
+ Agreement and does not cure such failure in a reasonable period of
233
+ time after becoming aware of such noncompliance. If all Recipient's
234
+ rights under this Agreement terminate, Recipient agrees to cease use
235
+ and distribution of the Program as soon as reasonably practicable.
236
+ However, Recipient's obligations under this Agreement and any licenses
237
+ granted by Recipient relating to the Program shall continue and survive.
238
+
239
+ Everyone is permitted to copy and distribute copies of this Agreement,
240
+ but in order to avoid inconsistency the Agreement is copyrighted and
241
+ may only be modified in the following manner. The Agreement Steward
242
+ reserves the right to publish new versions (including revisions) of
243
+ this Agreement from time to time. No one other than the Agreement
244
+ Steward has the right to modify this Agreement. The Eclipse Foundation
245
+ is the initial Agreement Steward. The Eclipse Foundation may assign the
246
+ responsibility to serve as the Agreement Steward to a suitable separate
247
+ entity. Each new version of the Agreement will be given a distinguishing
248
+ version number. The Program (including Contributions) may always be
249
+ Distributed subject to the version of the Agreement under which it was
250
+ received. In addition, after a new version of the Agreement is published,
251
+ Contributor may elect to Distribute the Program (including its
252
+ Contributions) under the new version.
253
+
254
+ Except as expressly stated in Sections 2(a) and 2(b) above, Recipient
255
+ receives no rights or licenses to the intellectual property of any
256
+ Contributor under this Agreement, whether expressly, by implication,
257
+ estoppel or otherwise. All rights in the Program not expressly granted
258
+ under this Agreement are reserved. Nothing in this Agreement is intended
259
+ to be enforceable by any entity that is not a Contributor or Recipient.
260
+ No third-party beneficiary rights are created under this Agreement.
261
+
262
+ Exhibit A - Form of Secondary Licenses Notice
263
+
264
+ "This Source Code may also be made available under the following
265
+ Secondary Licenses when the conditions for such availability set forth
266
+ in the Eclipse Public License, v. 2.0 are satisfied: {name license(s),
267
+ version(s), and exceptions or additional permissions here}."
268
+
269
+ Simply including a copy of this Agreement, including this Exhibit A
270
+ is not sufficient to license the Source Code under Secondary Licenses.
271
+
272
+ If it is not possible or desirable to put the notice in a particular
273
+ file, then You may include the notice in a location (such as a LICENSE
274
+ file in a relevant directory) where a recipient would be likely to
275
+ look for such a notice.
276
+
277
+ You may add additional accurate notices of copyright ownership.