def fromMatrix(stateObjs,*transProbsPerState): ''' returns a new Chain instance from given arguments stateObjs is a sequence of objects representing states (strings, usually); transProbsPerState arguments contain the transiiton probability weights; there is one such argument per state, it is a tuple (stateObj,transProbs) where transProbs is the sequence of probability weights of transition from stateObj to each declared state, in the order of their declarations ''' nextStateLeas = (Alea.fromValFreqs(*zip(stateObjs,transProbs)) for (stateObj,transProbs) in transProbsPerState) nextStateLeaPerState = tuple(zip(stateObjs,nextStateLeas)) return Chain(nextStateLeaPerState)
def __init__(self,*args): object.__init__(self) aClass = self.__class__ for (attrName,arg) in zip(aClass.__slots__,args): setattr(self,attrName,arg) length = len(str(arg)) maxLengthAttrName = '__maxLength' + attrName if length > getattr(aClass,maxLengthAttrName): setattr(aClass,maxLengthAttrName,length) aClass.__templateStr = "<%s>" % ', '.join("%s=%%%ds"%(attrName,getattr(aClass,'__maxLength'+attrName)) for attrName in aClass.__slots__)
def fromSeq(stateObjSeq): ''' returns a new Chain instance from given sequence of state objects the probabilities of state transitions are set according to transition frequencies in the given sequence ''' (fromStateObjIter,toStateObjIter) = tee(stateObjSeq); for _ in toStateObjIter: break nextStateObjsDict = dict() for (fromStateObj,toStateObj) in zip(fromStateObjIter,toStateObjIter): nextStateObjs = nextStateObjsDict.get(fromStateObj) if nextStateObjs is None: nextStateObjs = [] nextStateObjsDict[fromStateObj] = nextStateObjs nextStateObjs.append(toStateObj) nextStateNameAndObjs = list(nextStateObjsDict.items()) nextStateNameAndObjs.sort() nextStateLeaPerState = tuple((stateObj,Alea.fromVals(*nextStateObjs)) for (stateObj,nextStateObjs) in nextStateNameAndObjs) return Chain(nextStateLeaPerState)
def __str(self,formatFunc): ''' returns a string representation of the Markov chain with each state S followed by the indented representation of probability distribution of transition from S to next state formatFunc is a function to represent probability distribution, taking a Lea instance as argument and returning a string ''' nextStateLeas = (nextStateILea._lea1 for nextStateILea in self._nextStateBlea._iLeas) formattedNextStateLeas = (' -> ' + nextStateLea.map(str) for nextStateLea in nextStateLeas) return '\n'.join('%s\n%s'%(stateObj,formatFunc(formattedNextStateLea)) for (stateObj,formattedNextStateLea) in zip(self._stateObjs,formattedNextStateLeas))
def _genVPs(self): for (leaArg, factor) in zip(self._leaArgs, self._factors): for (v, p) in leaArg.genVPs(): yield (v, p * factor)