473,413 Members | 1,713 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,413 software developers and data experts.

Markov process representation

Here's one way (convert each set of transition percentages to
a running sum up to one):
import random

class SingleStateMarkov(object):
def __init__(self, probabilities, initial=None):
self._states = states = sorted(probabilities)
self._fromstate = dict([(name, n) for n, name in
enumerate(states)])
self._all_states = set(states)
self.transition = dict()
for name, row in probabilities.iteritems():
self.transition[name] = self.add_transitions(name, row)
if initial is None:
initial = self._states[0]
elif initial not in self._all_states:
raise ValueError('Invalid initial state %s' % initial)
self.state = initial

def add_transitions(self, name, row):
if set(row) - self._all_states:
raise ValueError('%s: moves to unknown states %s' % (
name, set(row) - self._all_states))
if min(row.values()) < 0:
raise ValueError('%s: bad odds for states %s' % (name,
[nm for nm,odds in row.iteritems() if odds < 0]))
total = float(sum(row.values())) # Sum of the odds.
if total <= 0:
raise ValueError('%s: No Transitions allowed' % name)
running_total = 0.
cumulative = []
for name in self._states:
running_total += row.get(name, 0.0)
cumulative.append(running_total / total)
return cumulative

def move(self):
v = random.random()
for index, entry in enumerate(self.transition[self.state]):
if v <= entry:
break
self.state = self._states[index]
return self.state
class MultiStateMarkov(SingleStateMarkov):
def __init__(self, probabilities, initial=None, order=2):
if [key for key in probabilities if len(key) != order]:
raise ValueError('State keys wrong size: %s' %
[key for key in probabilities
if len(key) != order])
self._all_states = set()
for i in range(order):
self._all_states |= set(key[i] for key in probabilities)
self._states = states = sorted(self._all_states)
self._fromstate = dict([(name, n) for n, name in
enumerate(states)])
self.transition = dict()
for key, row in probabilities.iteritems():
self.transition[key] = self.add_transitions(key, row)
if initial is None:
initial = (self._states[0],) * order
elif len(initial) != order or set(initial)-self._all_states:
raise ValueError('Invalid initial state %s' % initial)
self.state = initial

def move(self):
v = random.random()
for index, entry in enumerate(self.transition[self.state]):
if v <= entry:
break
state = self._states[index]
self.state = self.state[1:] + (state,)
return state
c = SingleStateMarkov(dict(A=dict(A=20, B=50, C=30),
B=dict(A=35, B=25, C=40),
C=dict(A=70, B=14, C=16)))

d = MultiStateMarkov(dict([(('A', 'A'), dict(A=15, B=55, C=30)),
(('A', 'B'), dict(A=20, B=45, C=35)),
(('A', 'C'), dict(A=60, B=30, C=10)),
(('B', 'A'), dict(A=35, B=25, C=40)),
(('B', 'B'), dict(A=49, B=48, C=3)),
(('B', 'C'), dict(A=60, B=20, C=20)),
(('C', 'A'), dict(A=5, B=75, C=20)),
(('C', 'B'), dict(A=0, B=90, C=10)),
(('C', 'C'), dict(A=70, B=14, C=16))]))
--Scott David Daniels
sc***********@acm.org
Mar 15 '06 #1
9 1288
This is wicked! I am trying to get it to work and am frantically fixing
tabs and spaces... but isn't line 50:

self._all_states |= set(key[i] for key in probabilities)

an error? isn't it supposed to be:

self._all_states != set(key[i] for key in probabilities)

Mar 15 '06 #2
kpp9c wrote:
This is wicked! I am trying to get it to work and am frantically fixing
tabs and spaces... It was cut and pasted from working code (which I pasted back to test).
but isn't line 50:

self._all_states |= set(key[i] for key in probabilities)

an error? isn't it supposed to be:

self._all_states != set(key[i] for key in probabilities)

Nope. self._all_states is a set. I am collecting all mentioned states
from the key. Another way to do it is:
self._all_states = set()
for key in probabilities:
self._all_states = set(key)
-- key is a order-tuple of states.

--Scott David Daniels
sc***********@acm.org
Mar 15 '06 #3
try as i might i still get an error:

File "markov.py", line 50
self._all_states |= set(key[i] for key in probabilities)
I am running:

Python 2.3 (#1, Sep 13 2003, 00:49:11)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin

If that helps any...

Thanks!

Mar 16 '06 #4
"kpp9c" <kp*@mac.com> writes:
self._all_states |= set(key[i] for key in probabilities)
I am running:
Python 2.3 (#1, Sep 13 2003, 00:49:11)


generator comprehensions are new in 2.4. Try:

self._all_states |= set([key[i] for key in probabilities])

This does temporarily use more memory.
Mar 16 '06 #5
On Wed, Mar 15, 2006 at 04:50:31PM -0800, Paul Rubin wrote:
"kpp9c" <kp*@mac.com> writes:
self._all_states |= set(key[i] for key in probabilities)
I am running:
Python 2.3 (#1, Sep 13 2003, 00:49:11)


generator comprehensions are new in 2.4. Try:

self._all_states |= set([key[i] for key in probabilities])


And sets aren't a builtin in 2.3

try:
set()
except NameError:
import sets
set = sets.Set

-Jack
Mar 16 '06 #6
yes looking at this code i see a few things i haven't seem before. I am
on Mac OS X 10.3.x and updating the python seems like a non trivial
task at the moment.. i will try that and see where that gets me. Thanks.

Mar 16 '06 #7
oh ... uhmm .. i don't follow what you are saying... where should i put
those lines... should the import thing go on top?

Mar 16 '06 #8
hee hee .... works fine ... but kinda slow on my old machine... really
time for a new laptop haha!

still this code is so beautiful! *^-^*

Mar 16 '06 #9
Jack Diederich wrote:
On Wed, Mar 15, 2006 at 04:50:31PM -0800, Paul Rubin wrote:
"kpp9c" <kp*@mac.com> writes:
self._all_states |= set(key[i] for key in probabilities)
I am running:
Python 2.3 (#1, Sep 13 2003, 00:49:11)


generator comprehensions are new in 2.4. Try:

self._all_states |= set([key[i] for key in probabilities])

And sets aren't a builtin in 2.3

try:
set()
except NameError:
import sets
set = sets.Set


nitpick:

try:
set
except NameError:
from sets import Set as set

--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science

Phone: +45 66 11 84 94
Mobile: +45 29 93 42 96
Mar 16 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: ujas_egroeg | last post by:
Hello, Our company has just started the implementation of process standards and I am facing a problem. I am told to represent our system where the browser calls the Applet. Like most HTMLS, ours...
3
by: dave | last post by:
Hi, Does anyone know how I could make an .exe launched server side from an aspx file run faster? When I use javascript client side it of couse is much faster. Here's my code This code does...
3
by: Brett | last post by:
Do ActiveX objects run in their own process or app domain? Referecing this article http://www.codeproject.com/buglist/iefix.asp, he gets events from ActiveX object to his IE object via...
11
by: pemo | last post by:
Ambiguous? I have a student who's asked me to explain the following std text (esp. the footnote). 6.2.6.1.5 Certain object representations need not represent a value of the object type. If...
5
by: kpp9c | last post by:
markov query I have noticed a couple markov implementations in python, but none quite seem to do what i would like. Most seem to do an analysis of some text and create a new text based on...
335
by: extrudedaluminiu | last post by:
Hi, Is there any group in the manner of the C++ Boost group that works on the evolution of the C language? Or is there any group that performs an equivalent function? Thanks, -vs
2
by: alacmathew | last post by:
Hi everybody I am a project manager with a mid level software development company Some days back I came across a posting in a forum where a person otherwise a competent finance professional wanted to...
3
by: emer.kurbegovic | last post by:
how can i get heap memory of a windows process with C#? For example, I would like to see the value of the heap memory allocated for my "java.exe" process. thanks in advance.
5
by: dave | last post by:
Hi Guys, I've written a Markov analysis program and would like to get your comments on the code As it stands now the final input comes out as a tuple, then list, then tuple. Something like...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.