Below is the file 'fritz.py' from this revision. You can also download the file.

#!/usr/bin/env python2.4

from mk2 import MarkovChain, MarkovState
import random
random.seed()
import cPickle
import getopt
import sys

def fritz_gen(fd, chain, max_bytes):
    def starting_point():
        # pick a starting point
        total = sum (map (lambda s : s.total, chain.states.values ()))
        choice = random.randint(0, total - 1)
        state = None
        for idx, state in enumerate (chain.states.values ()):
            choice -= state.total
            if choice <= 0:
                break
        return state
    # walk the markov, output stuff
    out_bytes = 0
    state = None
    # but let's have some cycle detection
    cycle_counts = {}
    while out_bytes < max_bytes:
        if state == None:
            state = starting_point()
        if state == None:
            # we're really out of ideas..
            break
        to_out = ''.join (state.state)
        if out_bytes + len(to_out) >= max_bytes:
            to_out = to_out[:max_bytes - out_bytes]
        fd.write (to_out)
        out_bytes += len(to_out)
        cycle_count = cycle_counts[id(state)] = cycle_counts.setdefault(id(state), 0) + 1
        if cycle_count > 5:
            state = None
            cycle_count = {}
        else:
            state = chain.random_next (state)
    fd.write('\n')

def log(s):
    print >>sys.stderr, s

def usage():
    print """\
Usage: %s [ --output=<file> ... ] [ --fritzfrom=<file> ] model.mk
  --output       specifies a file that should be generated from the model
  --fritzfrom    specifies a file that should be used as a basis for fritzing
                 (output is written to stdout)
"""

def get_fritzable(chain):
    def fritzable(s):
        return len (s.state) > 1
    log (chain.states.values())
    fritzable_states = filter (fritzable, chain.states.values())
    #log ("%s" % repr(map (lambda s : ''.join (s.state),  fritzable_states)))
    return fritzable_states

def fritz_file(fd, chain):
    find_states = get_fritzable(chain)


if __name__ == '__main__':
    try:
        optlist, args = getopt.getopt (sys.argv[1:], '', ['output=', 'fritzfile='])
    except getopt.GetoptError:
        usage()
        sys.exit(1)
    if len(args) != 1:
        usage()
        sys.exit(2)
    log("Loading %s" % args[0])
    chain = cPickle.load (open (args[0], 'rb'))
    for o, a in optlist:
        if o == '--output':
            log ("Writing fritz to %s." % (a))
            fritz_gen (open (a, 'wb'), chain, 1024)
        elif o == "--fritzfile":
            log ("Fritzing %s." % (a))