Skip to content

Commit

Permalink
seed for random model
Browse files Browse the repository at this point in the history
  • Loading branch information
Rapfff committed Jun 17, 2023
1 parent f534480 commit d7d210e
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 28 deletions.
10 changes: 6 additions & 4 deletions jajapy/base/Base_MC.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .Model import Model, MC_ID, MDP_ID, CTMC_ID
from numpy import ndarray, where
from random import choices
from random import choices, seed

class Base_MC(Model):
"""
Expand Down Expand Up @@ -123,7 +123,7 @@ def toStormpy(self):
except ModuleNotFoundError:
raise RuntimeError("Stormpy is not installed on this machine.")

def labelsForRandomModel(nb_states: int, labelling: list) -> list:
def labelsForRandomModel(nb_states: int, labelling: list, sseed:int=None) -> list:
if 'init' in labelling:
msg = "The label 'init' cannot be used: it is reserved for initial states."
raise SyntaxError(msg)
Expand All @@ -133,12 +133,14 @@ def labelsForRandomModel(nb_states: int, labelling: list) -> list:
print("number of states. The last labels will not be assigned to",end=" ")
print("any states.")


if nb_states > len(labelling):
print("WARNING: the size of the labelling is lower than the",end=" ")
print("number of states. The labels for the last states will",end=" ")
print("be chosen randomly.")


if sseed != None:
seed(sseed)
labelling = labelling[:min(len(labelling),nb_states)] + choices(labelling,k=nb_states-len(labelling))
labelling.append("init")
seed()
return labelling
3 changes: 2 additions & 1 deletion jajapy/base/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@ def randomProbabilities(size: int) -> ndarray:
raise ValueError("The size parameter should be higher than 0.")
if type(size) != int:
raise TypeError("The size parameter should be an int.")
return normalize(randint(1,11,size))
res = normalize(randint(1,11,size))
return res

def checkProbabilities(l: ndarray) -> bool:
"""
Expand Down
18 changes: 14 additions & 4 deletions jajapy/ctmc/CTMC.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from numpy.random import exponential
import numpy.random
from ast import literal_eval
from ..base.tools import resolveRandom, randomProbabilities
from ..base.Set import Set
Expand All @@ -7,7 +7,7 @@
from ..base.Base_MC import *
from math import exp, log
from random import randint
from numpy import array, zeros, dot, ndarray, vstack, hstack, newaxis, append, delete, where, insert
from numpy import array, zeros, dot, vstack, hstack, newaxis, delete, insert
from sys import platform
from multiprocessing import cpu_count, Pool
from sympy import sympify
Expand Down Expand Up @@ -175,7 +175,7 @@ def next(self,state: int) -> tuple:
if exp_lambda <= 0.0:
exps.append(1024)
else:
exps.append(exponential(1/exp_lambda))
exps.append(numpy.random.exponential(1/exp_lambda))
next_state= exps.index(min(exps))
next_obs = self.labelling[state]
return (next_obs, next_state, min(exps))
Expand Down Expand Up @@ -346,7 +346,8 @@ def loadCTMC(file_path: str) -> CTMC:

def CTMC_random(nb_states: int, labelling: list, min_exit_rate_time : int,
max_exit_rate_time: int, self_loop: bool = True,
random_initial_state: bool=True) -> CTMC:
random_initial_state: bool=True,
sseed:int=None) -> CTMC:
"""
Generates a random CTMC. All the rates will be between 0 and 1.
All the exit rates will be integers.
Expand All @@ -367,6 +368,8 @@ def CTMC_random(nb_states: int, labelling: list, min_exit_rate_time : int,
random_initial_state: bool, optional
If set to True we will start in each state with a random probability, otherwise we will always start in state 0.
Default is True.
sseed : int, optional
the seed value.
Returns
-------
Expand All @@ -392,6 +395,10 @@ def CTMC_random(nb_states: int, labelling: list, min_exit_rate_time : int,
s2 -> s0 : lambda = 0.2
s2 -> s1 : lambda = 0.8
"""
if sseed != None:
seed(sseed)
numpy.random.seed(sseed)

matrix = zeros((nb_states+1,nb_states))
for i in range(nb_states):
if self_loop:
Expand All @@ -411,6 +418,9 @@ def CTMC_random(nb_states: int, labelling: list, min_exit_rate_time : int,
matrix = hstack((matrix,zeros(len(matrix))[:,newaxis]))

labelling = labelsForRandomModel(nb_states,labelling)

seed()
numpy.random.seed()
return CTMC(matrix, labelling,"CTMC_random_"+str(nb_states)+"_states")

def createCTMC(transitions: list, labelling: list, initial_state,
Expand Down
17 changes: 12 additions & 5 deletions jajapy/gohmm/GoHMM.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from numpy.random import normal
import numpy.random
import random
from numpy import array, zeros, ndarray
from ast import literal_eval
from ..base.tools import randomProbabilities
from ..base.Base_HMM import Base_HMM, GOHMM_ID
from math import sqrt, exp, pi
from random import uniform

class GoHMM(Base_HMM):
"""
Expand Down Expand Up @@ -141,7 +141,7 @@ def next_obs(self, s:int) -> list:
output : str
An observation.
"""
return [normal(parameter[0],parameter[1],1)[0] for parameter in self.output[s]]
return [numpy.random.normal(parameter[0],parameter[1],1)[0] for parameter in self.output[s]]

def tau(self,s1:int,s2:int,obs: list) -> float:
"""
Expand Down Expand Up @@ -219,7 +219,7 @@ def loadGoHMM(file_path: str) -> GoHMM:
def GoHMM_random(nb_states:int,nb_distributions:int,
random_initial_state:bool=False,
min_mu: float=0.0,max_mu: float=2.0,
min_sigma: float=0.5,max_sigma: float=2.0) -> GoHMM:
min_sigma: float=0.5,max_sigma: float=2.0, sseed: int = None) -> GoHMM:
"""
Generates a random GoHMM.
Expand All @@ -243,6 +243,8 @@ def GoHMM_random(nb_states:int,nb_distributions:int,
lower bound for sigma. By default 0.5
max_sigma : float, optional
upper bound for sigma. By default 2.0
sseed : int, optional
the seed value.
Returns
-------
Expand All @@ -251,10 +253,13 @@ def GoHMM_random(nb_states:int,nb_distributions:int,
"""
matrix = []
output = []
if sseed != None:
random.seed(sseed)
numpy.random.seed(sseed)
for s in range(nb_states):
p1 = array(randomProbabilities(nb_states))
matrix.append(p1)
p2 = [[round(uniform(min_mu,max_mu),3),round(uniform(min_sigma,max_sigma),3)] for i in range(nb_distributions)]
p2 = [[round(random.uniform(min_mu,max_mu),3),round(random.uniform(min_sigma,max_sigma),3)] for i in range(nb_distributions)]
p2 = array(p2)
output.append(p2)
matrix = array(matrix)
Expand All @@ -264,6 +269,8 @@ def GoHMM_random(nb_states:int,nb_distributions:int,
init = randomProbabilities(nb_states)
else:
init = 0
numpy.random.seed()
random.seed()
return GoHMM(matrix, output, init,"GoHMM_random_"+str(nb_states)+"_states")


Expand Down
10 changes: 9 additions & 1 deletion jajapy/hmm/HMM.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from ..base.Base_HMM import Base_HMM,HMM_ID
from ast import literal_eval
from numpy import array, where, zeros
from numpy.random import seed

class HMM(Base_HMM):

Expand Down Expand Up @@ -180,7 +181,9 @@ def loadHMM(file_path: str) -> HMM:
return HMM(matrix, output, alphabet, initial_state, name)


def HMM_random(nb_states: int, alphabet: list, random_initial_state: bool = False) -> HMM:
def HMM_random(nb_states: int, alphabet: list,
random_initial_state: bool = False,
sseed: int = None) -> HMM:
"""
Generates a random HMM.
Expand All @@ -193,6 +196,8 @@ def HMM_random(nb_states: int, alphabet: list, random_initial_state: bool = Fals
random_initial_state: bool, optional
If set to True we will start in each state with a random probability, otherwise we will always start in state 0.
Default is False.
sseed : int, optional
the seed value.
Returns
-------
Expand All @@ -205,6 +210,8 @@ def HMM_random(nb_states: int, alphabet: list, random_initial_state: bool = Fals
"""
matrix = []
output = []
if sseed != None:
seed(sseed)
for s in range(nb_states):
p1 = array(randomProbabilities(nb_states))
matrix.append(p1)
Expand All @@ -217,6 +224,7 @@ def HMM_random(nb_states: int, alphabet: list, random_initial_state: bool = Fals
init = randomProbabilities(nb_states)
else:
init = 0
seed()
return HMM(matrix, output, alphabet, init,"HMM_random_"+str(nb_states)+"_states")


Expand Down
10 changes: 8 additions & 2 deletions jajapy/mc/MC.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from ..base.Base_MC import *
from ast import literal_eval
from numpy import ndarray, array, zeros, vstack, hstack, newaxis, append, where
from numpy.random import seed

class MC(Base_MC):
def __init__(self, matrix: ndarray, labelling: list, name: str ="unknown_MC") -> None:
Expand Down Expand Up @@ -225,7 +226,7 @@ def loadMC(file_path: str) -> MC:
f.close()
return MC(matrix, labelling, name)

def MC_random(nb_states: int, labelling: list, random_initial_state: bool=True) -> MC:
def MC_random(nb_states: int, labelling: list, random_initial_state: bool=True, sseed:int=None) -> MC:
"""
Generate a random MC.
Expand All @@ -239,6 +240,8 @@ def MC_random(nb_states: int, labelling: list, random_initial_state: bool=True)
If set to True we will start in each state with a random probability,
otherwise we will always start in state 0.
Default is True.
sseed : int, optional
the seed value.
Returns
-------
Expand All @@ -260,6 +263,8 @@ def MC_random(nb_states: int, labelling: list, random_initial_state: bool=True)
----STATE 2--init----
s2 -> s0 : 1.0
"""
if sseed != None:
seed(sseed)
matrix = []
for _ in range(nb_states):
matrix.append(append(randomProbabilities(nb_states),0.0))
Expand All @@ -269,7 +274,8 @@ def MC_random(nb_states: int, labelling: list, random_initial_state: bool=True)
else:
matrix.append(array([1.0]+[0.0 for i in range(nb_states)]))
matrix = array(matrix)
labelling = labelsForRandomModel(nb_states,labelling)
labelling = labelsForRandomModel(nb_states,labelling,sseed)
seed()
return MC(matrix, labelling,"MC_random_"+str(nb_states)+"_states")

def createMC(transitions: list, labelling: list, initial_state, name: str ="unknown_MC") -> MC:
Expand Down
20 changes: 15 additions & 5 deletions jajapy/mdp/MDP.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@
from ..base.Base_MC import *
from ..base.Set import Set
from .Scheduler import Scheduler
from numpy.random import geometric
from numpy import array, append, dot, zeros, vsplit, ndarray, where, reshape, vstack, append, concatenate
import numpy.random
from numpy import array, append, dot, zeros, vsplit, reshape, vstack, append, concatenate
from ast import literal_eval
from multiprocessing import cpu_count, Pool
from random import choices

class MDP(Base_MC):
"""
Expand Down Expand Up @@ -253,7 +252,7 @@ def generateSet(self, set_size: int, param, scheduler: Scheduler, distribution=N
val = []
for i in range(set_size):
if distribution == 'geo':
curr_size = min_size + int(geometric(param))
curr_size = min_size + int(numpy.random.geometric(param))
else:
if type(param) == list:
curr_size = param[i]
Expand Down Expand Up @@ -473,7 +472,9 @@ def loadMDP(file_path: str) -> MDP:
return MDP(matrix, labelling, actions, name)


def MDP_random(nb_states: int,labelling: list, actions: list,random_initial_state: bool = True, deterministic: bool = False) -> MDP:
def MDP_random(nb_states: int,labelling: list, actions: list,
random_initial_state: bool = True, deterministic: bool = False,
sseed: int = None) -> MDP:
"""
Generate a random MDP.
Expand All @@ -492,12 +493,17 @@ def MDP_random(nb_states: int,labelling: list, actions: list,random_initial_stat
If True, the model will be determinstic: in state `s`, with action `a`, for all label `o`,
there is at most one transition to a state labelled with `o`.
Default is False.
sseed : int, optional
the seed value.
Returns
-------
MDP
A pseudo-randomly generated MDP.
"""
if sseed != None:
seed(sseed)
numpy.random.seed(sseed)
alphabet = list(set(labelling))
matrix = []
for s in range(nb_states):
Expand All @@ -523,6 +529,10 @@ def MDP_random(nb_states: int,labelling: list, actions: list,random_initial_stat
matrix = array(matrix)

labelling = labelsForRandomModel(nb_states,labelling)

seed()
numpy.random.seed()

return MDP(matrix, labelling, actions, "MDP_random_"+str(nb_states)+"_states")


Expand Down
18 changes: 12 additions & 6 deletions jajapy/pctmc/PCTMC.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
from ..base.tools import resolveRandom
from ..base.Parametric_Model import *
from ..base.Set import Set
from numpy import ndarray, array, zeros, dot, newaxis, hstack, inf, vstack, delete
from numpy.random import exponential, rand
from numpy import zeros, dot, newaxis, hstack, inf, vstack, delete
from numpy.random import exponential, rand, seed
from math import exp, log
from multiprocessing import cpu_count, Pool
from sys import platform
from sympy import sympify

class PCTMC(Parametric_Model):
"""
Expand Down Expand Up @@ -207,7 +205,8 @@ def instantiate(self, parameters: list, values: list) -> bool:
return True
return False

def randomInstantiation(self, parameters: list = None,min_val:float = None,max_val:float = None) -> None:
def randomInstantiation(self, parameters: list = None,min_val:float = None,
max_val:float = None, sseed: int = None) -> None:
"""
Randomly instantiated the parameters given in `parameters`.
If `parameters` is not set it instantiates all the non-instantiated
Expand All @@ -229,6 +228,8 @@ def randomInstantiation(self, parameters: list = None,min_val:float = None,max_v
this value is equal to the parameters with the highest instantiation.
If not set and if the model has less than two instantiated parameters,
this value is equal to 5.0.
sseed : int, optional
the seed value.
"""
if parameters == None:
parameters = []
Expand All @@ -247,10 +248,15 @@ def randomInstantiation(self, parameters: list = None,min_val:float = None,max_v
max_val = max(self.parameter_values.values())
else:
max_val = 0.3

if sseed != None:
seed(sseed)
val = rand(len(parameters))*(max_val-min_val)+min_val
while not self.instantiate(parameters,val):
val = rand(len(parameters))*(max_val-min_val)+min_val


seed()

def _stateToString(self,state:int) -> str:
res = "----STATE "+str(state)+"--"+self.labelling[state]+"----\n"
if self.isInstantiated(state):
Expand Down

0 comments on commit d7d210e

Please sign in to comment.