mardi 9 août 2022

Python random setState and getState to file

I am trying to save the current random generator state of application to replicate a lot of random action taken during the process.

import random
import pickle
from Model import Resnet
def main():
    fileName = "09-08-2022T200803"
    with open("data/" + fileName + ".txt", "rb") as rb:
        data = pickle.load(rb)
        random.setstate(data[0][0])
#data[0][0] is some saved seed object, the file is only appended, it is always the same object

    myNetwork = Resnet.Network()
    model = myNetwork.getModel()

    playGame(model, 4, fileName)
Turn: 14, Action:251
Turn: 15, Action:33
Turn: 15, Action:186
Turn: 15, Action:16
GAME_FINISHED

However, when I close the program and run it again, the results differ:

Turn: 13, Action:251
Turn: 14, Action:29
Turn: 14, Action:251
Turn: 15, Action:33
GAME_FINISHED

Can it be done so I will keep the random generator state in file so I can debug the particular game that didn't work? (Game is 100% random as for now)

I have already tried to random.setstate() just before game and run it several times in the same application(in a loop) and it did play exactly the same games, however - when I rerun(stop->run) the program, it did not work, results differed between application runs (probably because it was after Resnet.Network() initialization)

The different approach which gave me exact the same results in one application run, but still different in between runs:

def main():
    myNetwork = Resnet.Network()
    model = myNetwork.getModel()

    fileName = "09-08-2022T200803"
    with open("data/"+fileName+".txt", "rb") as rb:
        while True:
            data = pickle.load(rb)
            playGame(model, 4, fileName, data[0][0])
#data[0][0] is same object each time I read the file(that's how its saved), therefore it works in single application run



def playGame(model, simulations, fileName, seedObject = None):
    if seedObject != None:
        random.setstate(seedObject)
    # ... game



Aucun commentaire:

Enregistrer un commentaire