コード例 #1
0
def main(args):
    states = read_states(args.input)

    stats = Stats(sys.argv)
    cipher = Spritz()

    settings = Settings(args)

    prompt_step = max(1, len(states) // 20)
    i = 0
    for initial_state, revealed_state, prefix_length in states:
        if args.verbosity > 1 and i % prompt_step == 0:
            print('test #:', i)
        i += 1

        KNOWN_KEYSTREAM_SIZE = 3 * initial_state.size
        cipher.initialize_state(initial_state.state)
        known_keystream = cipher.keystream(prefix_length + KNOWN_KEYSTREAM_SIZE)
        settings.prefix_length = prefix_length

        # in case we want to skip less keystream than revealed_state is
        # generate in, we cut off beginning of keystream and move 
        # initial_state apropriatelly
        if args.input and args.force_prefix_length and args.force_prefix_length < prefix_length:
            new_prefix_length = args.force_prefix_length
            new_start_offset = prefix_length - new_prefix_length
            settings.prefix_length = new_prefix_length
            known_keystream = known_keystream[new_start_offset:]   
            cipher.initialize_state(initial_state.state)
            cipher.keystream(new_start_offset)
            initial_state = SpritzState(cipher.state)

        cipher.initialize_state(initial_state.state)
        cipher.keystream(prefix_length)
        found_state, round_stats = backtrack.kpa(
            known_keystream,
            revealed_state,
            settings,
        )

        if found_state and initial_state != found_state:
            print('incorrect result, this should not happen')
            assert False

        stats.add(round_stats)

    stats.print_stats(args.verbosity)
    # dump pickled stats object
    if not args.no_stats_log:
        timestamp = datetime.datetime.today().strftime('%y%m%d_%H%M%S_%f')
        os.makedirs('stats/', exist_ok=True)
        with open('stats/' + timestamp, 'wb') as f:
            pickle.dump(stats, f)
コード例 #2
0
ファイル: game.py プロジェクト: henriquecscode/casino_nn
class Casino:

    NO_ITERATIONS = 1000
    NO_GENERATIONS = 50
    TEST_ITERATIONS = 100
    INITIAL_ITERATIONS = 1000
    DATA_LEN = 1000
    pop = None
    rng = 0
    KEYS = ["-training", "-pop_size", "-initializion_size"]
    PAYOUTS = {5: 24.6250, 6: 19.7, 7: 16.4166, 8: 14.0714, 9: 12.3125, 10: 10.9444, 11: 9.8500, 12: 8.9545, 13: 8.2083, 14: 7.5769, 15: 7.0357, 16: 6.5666, 17: 6.1562, 18: 5.7941, 19: 5.4722, 20: 5.1842, 21: 4.9250, 22: 4.6904, 23: 4.4772, 24: 4.2826, 25: 4.1041, 26: 3.9400, 27: 3.7884, 28: 3.6481, 29: 3.5178, 30: 3.3965, 31: 3.2833, 32: 3.1774, 33: 3.0781, 34: 2.9848, 35: 2.8970, 36: 2.8142, 37: 2.7361, 38: 2.6621, 39: 2.5921, 40: 2.5256, 41: 2.4625, 42: 2.4024, 43: 2.3452, 44: 2.2906, 45: 2.2386, 46: 2.1888, 47: 2.1413, 48: 2.0957, 49: 2.0520, 50: 2.0102,
               51: 1.9700, 52: 1.9213, 53: 1.8942, 54: 1.8584, 55: 1.8240, 56: 1.7909, 57: 1.7589, 58: 1.7280, 59: 1.6982, 60: 1.6694, 61: 1.6416, 62: 1.6147, 63: 1.5887, 64: 1.5634, 65: 1.5390, 66: 1.5153, 67: 1.4924, 68: 1.4701, 69: 1.4485, 70: 1.4275, 71: 1.4071, 72: 1.3873, 73: 1.3680, 74: 1.3493, 75: 1.3310, 76: 1.3133, 77: 1.2960, 78: 1.2792, 79: 1.2628, 80: 1.2468, 81: 1.2312, 82: 1.2160, 83: 1.2012, 84: 1.1867, 85: 1.1726, 86: 1.1588, 87: 1.1453, 88: 1.1321, 89: 1.1193, 90: 1.1067, 91: 1.0944, 92: 1.0824, 93: 1.0706, 94: 1.0591, 95: 1.0478, 96: 1.0368}


    def __init__(self, args):
        definitions = self.definitions(args)
        self.execute(definitions)

    def definitions(self, args):
        definitions = []
        if args.training == None:
            training = ""
            while training not in ["t", "e"]:
                training = input("enter t for training or e for examination/test")
            training = training == "t"
        else:
            training = args.training

        if args.initialized == None:
            num_ais = -1
            while num_ais < 0 or num_ais > 10:
                num_ais = int(input("how many ais you want to already be initalized"))
        else:
            initialized = args.initialized

        if args.pop_size == None:
            pop_size = -1
            while pop_size < 0 or pop_size > 100:
                pop_size = int(input("How many ais the population should be made of"))
        else:
            pop_size = args.pop_size

        return [training, initialized, pop_size]
    def execute(self, definitions):
        training, initialized, pop_size = definitions
        self.pop = Population(save_size = initialized, population_size=pop_size)
        self.setupInitialState()

        if training:
            self.runTraining()
        else:
            self.runTest()

        self.results()

    def setupInitialState(self):
        
        self.data_results = Stats(self.DATA_LEN)


        print('Setting initial state')
        for _ in range(self.INITIAL_ITERATIONS):
            self.getRandom()
            self.data_results.add(self.rng)

        print('Initial state set')

    def runTraining(self):
        for i in range(self.NO_GENERATIONS):
            print('Generation', i+1 )
            self.runGeneration()
        self.pop.savePop()

    def runTest(self):
        for _ in range(self.TEST_ITERATIONS):
            self.runAis()
        self.pop.fitness()

    def runGeneration(self):
        for _ in range(self.NO_ITERATIONS):
            self.runAis()
        self.pop.updateAis()
        
    def runAis(self):
        self.getRandom()
        self.updateStats()
        self.game_state = self.getGameState()

        '''
        #Multiprocessing
        pool = mp.Pool(mp.cpu_count())
        pool.map_async(self.handleAiBet, [ai for ai in self.pop.population])
        pool.close()
        pool.join()
        '''
        #No multiprocessing
        self.handleAllBet()

    def handleAllBet(self):
        for ai in self.pop.population:
            self.handleAiBet(ai)

    def handleAiBet(self, ai):
        bet = ai.askForBet(self.game_state[:])
        profit = self.decideBet(bet)
        ai.betResult(profit)

    def decideBet(self, bet):
        number = bet[0]
        wage = bet[1]
        lower = bet[2]
        if lower > 0: # We win if obtain a lower number
            return -wage if number >= self.rng else (self.PAYOUTS[number]-1) * wage
        return -wage if number <= self.rng else (self.PAYOUTS[number] - 1) * wage

    def getRandom(self):
        self.rng = random.randint(1, 100)

    def getGameState(self):
        return [self.data_results.getAverage(), self.data_results.getStdev(), self.data_results.getSkew()]

    def updateStats(self):
        self.data_results.add(self.rng)
        # Sets of stats that are kept about the progress of the chain of RNGs

    def results(self):
        print("Finished execution")
        print([x.balance for x in self.pop.population])
        #input()
        #print([x.record_number for x in self.pop.population])
        #input()
        #print([x.record_amount for x in self.pop.population])
        plt.plot([i for i in range(len(self.pop.population[0].record_balance))], np.transpose([x.record_balance for x in self.pop.population]))
        plt.show()
        input("Enter any string to continue")
コード例 #3
0
ファイル: game_ai.py プロジェクト: henriquecscode/casino_nn
class GameAi(object):

    layers = [6, 10, 10, 3]
    DATA_LEN = 20

    def __init__(self, model=None):

        if model is None:
            self.nn = self.model()
        else:
            self.nn = model
        self.getLayers()
        self.fitness = 0
        self.reset()

    def reset(self):
        #Specific to ai game state data
        self.prediction = None
        self.balance = 0

        #To calculate fitness
        self.game_state = None

        #Stats (Used to prediction)
        self.wins = []
        self.bet_amount = Stats(20)
        self.bet_number = Stats(20)
        self.losses_in_a_row = 0

        #Stats (Used just for debug)
        self.record_number = []
        self.record_amount = []
        self.record_balance = []

    def model(self):
        "returns a neural network for training"
        inputs = Input(shape=[self.layers[0]], name='input')
        network = Dense(self.layers[1], activation='sigmoid')(inputs)
        for i in range(2, len(self.layers) - 1):
            network = Dense(self.layers[i], activation='sigmoid')(network)

        #Output layer: Number, Wage
        network = Dense(self.layers[len(self.layers) - 1],
                        activation='linear')(network)

        model = Model(inputs=inputs, outputs=network)
        opt = Adam(0.01)
        model.compile(loss='mean_squared_error',
                      optimizer=opt,
                      metrics=['mse'])

        return model

    def betResult(self, profit):

        self.balance += profit
        self.record_balance.append(self.balance)
        if profit < 0:
            self.losses_in_a_row += 1
        else:
            self.losses_in_a_row = 0
        pass
        #deal with bet result

    def askForBet(self, game_state):
        bet_state = self.getBetState(game_state)

        bet_state = np.array([bet_state])
        self.prediction = self.nn.predict(bet_state)

        #predition = [number, wage, if we are betting the number will be lower]
        #self.prediction.append(1) #for now, the ai only decides number and wage

        number = abs(self.prediction[0][0] * 100)
        number = 5 if number < 5 else 96 if number > 96 else number
        number = round(number)
        wage = abs(self.prediction[0][1])
        lower = self.prediction[0][2]

        self.bet_amount.add(wage)
        self.bet_number.add(number)
        self.record_amount.append(wage)
        self.record_number.append(number)

        return [number, wage, lower]

    def getBetState(self, game_state):
        game_state.extend([
            self.losses_in_a_row,
            self.bet_amount.getAverage(),
            self.bet_number.getStdev()
        ])
        return game_state

    def reproduce(self, ai):
        new_weights = []
        for x in range(len(self.weights)):
            new_weights.append(
                self.weights[x] if random.random() > 0.5 else ai.weights[x])
            #Randomizes betweeen a weight from this ai or from the one it is beeing reproduced with

        return new_weights

    def decompressWeights(self):
        weights = self.nn.get_weights()
        new_weights = []
        for x in range(len(weights)):
            if (x % 2 == 0):
                layer = weights[x]
                for node in layer:
                    for conn in node:
                        new_weights.append(conn)
        self.weights = new_weights

    def compressWeights(self, weights):

        counter = 0
        new_weights = []
        for i in range(len(self.layers) - 1):
            layer_weights = []
            for j in range(self.layers[i]):
                node_weights = []
                for k in range(self.layers[i + 1]):
                    node_weights.append(weights[counter])
                    counter += 1
                layer_weights.append(node_weights)
            new_weights.append(np.array(layer_weights))
            new_weights.append(np.zeros(self.layers[i + 1]))
        return new_weights

    def setWeights(self, new_weights):
        compressed_weights = self.compressWeights(new_weights)
        self.nn.set_weights(compressed_weights)

    def getLayers(self):
        weights = self.nn.get_weights()
        layers = []
        layers.append(len(weights[0]))
        for x in range(len(weights)):
            if x % 2 == 0:
                layers.append(np.size(weights[x][0]))
        print(layers)