[Sampling] CFTPを勉強しよう(その1)


題材は「完璧にサンプリングしよう!」です。来嶋先生のページで中身が公開されています(参考: 直リンク / 先生のページ

題材を真似して打ち切りを行う部分を作りました。記事の中身を真似して、更新関数はサイコロ風にハードコーディングしてあります。

import numpy as np
np.random.seed(0)

def random2dice(u):
    return int(u * 6.0) + 1

x = np.random.rand(100)
dice = [random2dice(u) for u in x]

update_table = {
    1: [0, 0, 2],  # サイコロ1では状態0→0, 1→0, 2→2
    2: [1, 0, 1],
    3: [1, 0, 2],
    4: [2, 1, 1],
    5: [1, 2, 2],
    6: [0, 2, 0]
}

fix_list = [-1.0, 3.9/6.0, 5.9/6.0,  
2.9/6.0, 3.9/6.0, 4.9/6.0, 0.0, 0.0, 0.0, 0.0, 0.0]
def cftp(states=3, max_iter = 4, verbose=False):
    T = -1
    llbd = []
    ldice = []
    counter = 0
    
    while True:
        counter += 1
        # lbd = np.random.rand()
        lbd = fix_list[counter]
        llbd.insert(0, lbd)
        ldice.insert(0, random2dice(lbd))
        ls = [i for i in range(states)]
        for dice in ldice:
            for i, st in enumerate(ls):
                new_state = update_table[dice][st]
                ls[i] = new_state
        if verbose:
            print(ldice, "\tTo: ", list(map(lambda v: str(v+1), ls)))
            
        dd = {}
        for elem in ls: 
            dd[elem] = 1
        if len(dd.keys()) == 1:
            return list(dd.keys())[0]
stop = cftp() 
print(stop)

verboseをTrueにして渡すと、いろいろ結果が代わります。

[4] 	To:  ['3', '2', '2']
[6, 4] 	To:  ['3', '2', '3']
[1, 6, 4] 	To:  ['3', '3', '3']
2
[4] 	To:  ['3', '2', '2']
[3, 4] 	To:  ['2', '3', '2']
[4, 3, 4] 	To:  ['2', '3', '3']
[3, 4, 3, 4] 	To:  ['3', '2', '3']
[2, 3, 4, 3, 4] 	To:  ['2', '3', '2']
[1, 2, 3, 4, 3, 4] 	To:  ['2', '2', '2']
1