def _gen_samples(self):
        result = []
        self.price_feature_mention = Construction.construct_price_feature(self.tensor_train, self.dataModel)
        for user, user_df in self.price_feature_mention.iteritems():
            for ix in xrange(len(user_df)):
                row = user_df[ix]
                if sum(row):
                    nonzero = row.nonzero()[0]
                    up_result = []
                    while len(up_result) < len(nonzero):
                        sample_i = random.choice(nonzero)

                        sample_j = random.choice(range(self.num_features))
                        while row[sample_i] <= row[sample_j]:
                            sample_j = random.choice(xrange(self.num_features))

                        jx = random.choice(range(self.num_prices))
                        random_time = 0
                        while user_df[ix][sample_i] <= user_df[jx][sample_i] and random_time < self.num_prices:
                            jx = random.choice(range(self.num_prices))
                            random_time += 1

                        if random_time >= self.num_prices:
                            break

                        up_result.append((ix, jx, sample_i, sample_j))
            result.append((user, up_result))
        return result
    def fit(self, trainSamples, trainTargets):
        self.dataModel = MemeryDataModel(trainSamples, trainTargets)
        data = np.array(self.dataModel.getData().todense())
        u,s,v = isvd(data)
        new_data = np.dot(u, np.dot(s, v))
        new_data[new_data < 1] = np.nan
        u,s,v = isvd(new_data)
        new_data = np.dot(u, np.dot(s, v))
        #new_data[new_data < 1] = 0
        self.mf_rate = new_data

        train_data = pd.DataFrame(trainSamples, columns=['user', 'item', 'price'])
        item_price = dict(zip(train_data.ix[:,'item'], train_data.ix[:,'price']))
        data = train_data.groupby('user').mean()
        self.personal_item_price = np.empty((self.dataModel.getUsersNum(), self.dataModel.getItemsNum()))
        for user_ix in xrange(self.dataModel.getUsersNum()):
            user_avg_price = data.loc[self.dataModel.getUserByUid(user_ix), 'price']
            for item_ix in xrange(self.dataModel.getItemsNum()):
                delta_item_price = (item_price[self.dataModel.getItemByIid(item_ix)] - user_avg_price) / user_avg_price
                self.personal_item_price[user_ix][item_ix] = item_price[self.dataModel.getItemByIid(item_ix)]

        b = {'phones':train_data}
        price_df = Construction.get_user_category_buy_price(b)
        self.param_mu, self.param_sigm = MyGaussian.gaussian_curve_fit(price_df)

        self.alpha = np.random.rand(self.dataModel.getUsersNum())
        self.beta = np.random.rand(self.dataModel.getUsersNum())
        self.gamma = np.zeros(self.dataModel.getUsersNum())

        origin_lambda_iter = self.lambda_iter
        for user_ix in xrange(self.dataModel.getUsersNum()):
            samples = self.sample(user_ix, self.max_iter)
            self.lambda_iter = origin_lambda_iter
            old_target_value = 0
            for item_1, item_2 in samples:
                new_alpha, new_beta = self.update(user_ix, item_1, item_2)

                ##if not old_target_value or old_target_value < target_value:
                    #old_target_value = target_value
                self.alpha[user_ix] = new_alpha
                self.beta[user_ix] = new_beta
                self.lambda_iter = self.lambda_iter * 0.9
                #else:
                    #break
                #print user_ix, target_value

                #self.gamma[user_ix] = new_gamma
                #print user_ix, self.target_value(user_ix)

            #print user_ix, self.target_value(user_ix)
        self.lambda_iter = origin_lambda_iter
        self.beta = np.zeros(self.dataModel.getUsersNum())
    def fit(self, trainSamples, trainTargets):
        self.trainDataFrame = pd.DataFrame(trainSamples, columns = ['user', 'item', 'price_ix', 'price', 'feature', 'rate'])
        self.item_price_ix_dict = self.trainDataFrame.set_index('item')['price_ix'].to_dict()
        self.dataModel = MyMemeryDataModel.MemeryDataModel(trainSamples, trainTargets)

        tensor_model = TensorFactorization.TensorBPR(self.trainDataFrame, self.dataModel, self.implict_dim_num, self.max_iter, self.pf_lambda, self.train_sentry, self.learning_rate, self.regularization)
        user_price_feature_tensor = tensor_model.train()

        '''
        for price_feature in user_price_feature_tensor:
            for features in price_feature:
                feature_ix = sorted(range(self.dataModel.getFeaturesNum()), key=lambda x: features[x], reverse=True)[self.most_like_feature_num:]
                features[feature_ix] = 0
        '''
        item_feature = Construction.construct_item_feature(self.trainDataFrame, self.dataModel)

        self.user_price_item_tensor = np.dot(user_price_feature_tensor, item_feature.transpose())

        return self.user_price_item_tensor
    num_factors = 50
    f_tmp = 0
    model = TensorBPR(num_factors)
    num_iters = 10000
    model.train(num_iters)
    '''
    a = pd.read_csv('a').values
    b = pd.read_csv('b').values
    c = pd.read_csv('c').values
    d = pd.read_csv('d').values
    len1 = 689
    len2 = 1036
    len3 = 172
    tensor = np.empty((len1, len2, len3))

    for ix in range(len1):
        for rx in range(len2):
            tmp = np.dot(a[ix,:], b[rx,:])
            for cx in range(len3):
                tensor[ix, rx, cx] = np.dot(a[ix,:], c[cx,:]) + np.dot(b[rx,:], d[cx,:]) + tmp

    data = pd.read_csv('~/Documents/coding/dataset/workplace/filter_phones_train.csv')
    item_feature = Construction.construct_item_feature(data, len2, len3)

    result = np.dot(tensor, item_feature)
    print result




示例#5
0
def putTheirInventory(inventory):
    inventory.constrs.append(Construction((0, 7), ANTHILL))
    inventory.constrs.append(Construction((1, 7), TUNNEL))
    queen = Ant((0, 7), QUEEN, PLAYER_TWO)
    queen.health = 1
    inventory.ants.append(queen)  # Queen
示例#6
0
def main():
    a = pd.read_csv('../../../dataset/workplace/filter_phones_format.csv')
    b = {'phones':a}
    price_df = Construction.get_user_category_buy_price(b)
    param_mu, param_sigm = MyGaussian.gaussian_curve_fit(price_df)
    print min(param_sigm['phones']), max(param_sigm['phones'])
示例#7
0
def getNextState(currentState, move):
    # variables I will need
    myGameState = currentState.fastclone()
    myInv = getCurrPlayerInventory(myGameState)
    me = myGameState.whoseTurn
    myAnts = myInv.ants

    # If enemy ant is on my anthill or tunnel update capture health
    myTunnels = myInv.getTunnels()
    myAntHill = myInv.getAnthill()
    for myTunnel in myTunnels:
        ant = getAntAt(myGameState, myTunnel.coords)
        if ant is not None:
            opponentsAnts = myGameState.inventories[not me].ants
            if ant in opponentsAnts:
                myTunnel.captureHealth -= 1
    if getAntAt(myGameState, myAntHill.coords) is not None:
        ant = getAntAt(myGameState, myAntHill.coords)
        opponentsAnts = myGameState.inventories[not me].ants
        if ant in opponentsAnts:
            myAntHill.captureHealth -= 1

    # If an ant is built update list of ants
    antTypes = [WORKER, DRONE, SOLDIER, R_SOLDIER]
    if move.moveType == BUILD:
        if move.buildType in antTypes:
            ant = Ant(myInv.getAnthill().coords, move.buildType, me)
            myInv.ants.append(ant)
            # Update food count depending on ant built
            if move.buildType == WORKER:
                myInv.foodCount -= 1
            elif move.buildType == DRONE or move.buildType == R_SOLDIER:
                myInv.foodCount -= 2
            elif move.buildType == SOLDIER:
                myInv.foodCount -= 3

    # If a building is built update list of buildings and the update food count
    if move.moveType == BUILD:
        if move.buildType == TUNNEL:
            building = Construction(move.coordList[0], move.buildType)
            myInv.constrs.append(building)
            myInv.foodCount -= 3

    # If an ant is moved update their coordinates and has moved
    if move.moveType == MOVE_ANT:
        newCoord = move.coordList[len(move.coordList) - 1]
        startingCoord = move.coordList[0]
        for ant in myAnts:
            if ant.coords == startingCoord:
                ant.coords = newCoord
                ant.hasMoved = False
                # If an ant is carrying food and ends on the anthill or tunnel drop the food
                if ant.carrying and ant.coords == myInv.getAnthill().coords:
                    myInv.foodCount += 1
                    ant.carrying = False
                for tunnels in myTunnels:
                    if ant.carrying and (ant.coords == tunnels.coords):
                        myInv.foodCount += 1
                        ant.carrying = False
                # If an ant doesn't have food and ends on the food grab food
                if not ant.carrying:
                    foods = getConstrList(myGameState, None, (FOOD,))
                    for food in foods:
                        if food.coords == ant.coords:
                            ant.carrying = True
                # If my ant is close to an enemy ant attack it
                adjacentTiles = listAdjacent(ant.coords)
                for adj in adjacentTiles:
                    if getAntAt(myGameState, adj) is not None:  # If ant is adjacent my ant
                        closeAnt = getAntAt(myGameState, adj)
                        if closeAnt.player != me:  # if the ant is not me
                            closeAnt.health = closeAnt.health - UNIT_STATS[ant.type][ATTACK]  # attack
                            # If an enemy is attacked and looses all its health remove it from the other players
                            # inventory
                            if closeAnt.health <= 0:
                                enemyAnts = myGameState.inventories[not me].ants
                                for enemy in enemyAnts:
                                    if closeAnt.coords == enemy.coords:
                                        myGameState.inventories[not me].ants.remove(enemy)
                            # If attacked an ant already don't attack any more
                            break
    return myGameState
示例#8
0
def putOurInventory(inventory):
    inventory.constrs.append(Construction((0, 3), ANTHILL))
    inventory.constrs.append(Construction((1, 3), TUNNEL))
    inventory.ants.append(Ant((0, 3), QUEEN, PLAYER_ONE))  # Queen
    inventory.ants.append(Ant((0, 6), DRONE, PLAYER_ONE))  # Queen
示例#9
0
#IMPORTS
import Login
import Village
import Construction
from pprint import pprint
import time
import random
#_______________________________________________________________________________
#CONSTANTS
HOMEPAGE = 'https://ts3.travian.it/dorf1.php'
#_______________________________________________________________________________

#create browser
driver = Login.login()
#my_vs is a list wih a Village object for each village in the account
my_vs = Village.villages_create(driver)
print my_vs[0]

building_list = [{'identifier': 2, 'lvl': 2}, {'identifier': 3, 'lvl': 1}]
while True:
    #my_vs is a list wih a Village object for each village in the account
    my_vs = Village.villages_create(driver)
    Construction.construct(my_vs[0], building_list)
    time.sleep(random.randint(60, 120))
示例#10
0
    def getFutureState(self, currentState, move):
        # create a bare-bones copy of the state to modify
        newState = currentState.fastclone()

        # get references to the player inventories
        playerInv = newState.inventories[newState.whoseTurn]
        enemyInv = newState.inventories[1 - newState.whoseTurn]

        if move.moveType == BUILD:
            # BUILD MOVE
            if move.buildType < 0:
                # building a construction
                playerInv.foodCount -= CONSTR_STATS[move.buildType][BUILD_COST]
                playerInv.constrs.append(
                    Construction(move.coordList[0], move.buildType))
            else:
                # building an ant
                playerInv.foodCount -= UNIT_STATS[move.buildType][COST]
                playerInv.ants.append(
                    Ant(move.coordList[0], move.buildType, newState.whoseTurn))

        elif move.moveType == MOVE_ANT:
            # MOVE AN ANT
            # get a reference to the ant
            ant = getAntAt(newState, move.coordList[0])

            # update the ant's location after the move
            ant.coords = move.coordList[-1]
            ant.hasMoved = True

            # get a reference to a potential construction at the destination coords
            constr = getConstrAt(newState, move.coordList[-1])

            # check to see if a worker ant is on a food or tunnel or hill and act accordingly
            if constr and ant.type == WORKER:
                # if destination is food and ant can carry, pick up food
                if constr.type == FOOD:
                    if not ant.carrying:
                        ant.carrying = True
                # if destination is dropoff structure and and is carrying, drop off food
                elif constr.type == TUNNEL or constr.type == ANTHILL:
                    if ant.carrying:
                        ant.carrying = False
                        playerInv.foodCount += 1

            # get a list of the coordinates of the enemy's ants
            enemyAntCoords = [enemyAnt.coords for enemyAnt in enemyInv.ants]

            # contains the coordinates of ants that the 'moving' ant can attack
            validAttacks = []

            # go through the list of enemy ant locations and check if
            # we can attack that spot, and if so add it to a list of
            # valid attacks (one of which will be chosen at random)
            for coord in enemyAntCoords:
                if UNIT_STATS[ant.type][RANGE]**2 >= abs(
                        ant.coords[0] - coord[0])**2 + abs(ant.coords[1] -
                                                           coord[1])**2:
                    validAttacks.append(coord)

            # if we can attack, pick a random attack and do it
            if validAttacks:
                enemyAnt = getAntAt(newState, random.choice(validAttacks))
                attackStrength = UNIT_STATS[ant.type][ATTACK]

                if enemyAnt.health <= attackStrength:
                    # just to be safe, set the health to 0
                    enemyAnt.health = 0
                    # remove the enemy ant from their inventory
                    enemyInv.ants.remove(enemyAnt)
                else:
                    # lower the enemy ant's health because they were attacked
                    enemyAnt.health -= attackStrength

        # return the modified copy of the original state
        return newState
示例#11
0
#IMPORTS
from selenium import webdriver
import Login
import Construction
from village_module import Village
from adventures_module import Adventures
#_______________________________________________________________________________
HOMEPAGE = 'https://tx3.travian.pt/dorf1.php'
#_______________________________________________________________________________

#Create DRIVER
driver = webdriver.Chrome()     #usefull for testing
#driver = webdriver.PhantomJS() #usefull for automation (silent driver)

#do login -> directs to main village
driver = Login.login(driver)

#get village status
driver.get(HOMEPAGE)
#my_village = Village.Village(driver, HOMEPAGE)

#here comes the real scripting part
while True:
    #Try to construct stuff
    Construction.construct(driver, HOMEPAGE)
    #DO OTHER STUFF

#adventures = Adventures.adventures_do(driver)

driver.quit()
示例#12
0
    def getFutureState(self, currentState, nextMove):
        """
        :type currentState: GameState
        :type nextMove: Move
        :rtype: GameState
        """

        # for ending turns, there is no change to the board
        if nextMove.moveType == END:
            return currentState

        futureState = currentState.fastclone()
        """:type : GameState"""

        playerId = currentState.whoseTurn
        enemyId = playerId * (-1) + 1

        if nextMove.moveType == BUILD:
            if nextMove.buildType == TUNNEL:
                futureState.inventories[playerId].foodCount -= CONSTR_STATS[
                    TUNNEL][BUILD_COST]
                futureState.inventories[playerId].constrs.append(
                    Construction(nextMove.coordList[0], nextMove.buildType))
            else:
                # build an ant
                futureState.inventories[playerId].foodCount -= UNIT_STATS[
                    nextMove.buildType][COST]
                futureState.inventories[playerId].ants.append(
                    Ant(nextMove.coordList[0], nextMove.buildType, playerId))

        else:
            # the move is a MOVE_ANT move, so
            # find the ant and move it to the target
            ant = getAntAt(futureState, nextMove.coordList[0])
            """:type : Ant"""
            ant.coords = nextMove.coordList[-1]

            # see if it moved onto a structure
            constr = getConstrAt(futureState, nextMove.coordList[-1])

            if constr and ant.type == WORKER:
                # pickup/dropoff food
                if ant.carrying and (constr.type == ANTHILL
                                     or constr.type == TUNNEL):
                    ant.carrying = False
                    futureState.inventories[playerId].foodCount += 1
                elif not ant.carrying and constr.type == FOOD:
                    ant.carrying = True

            # search for possible attacks and execute one
            for coords in listAdjacent(ant.coords):

                targetAnt = getAntAt(futureState, coords)
                """:type : Ant"""

                # verify that the targetAnt is an enemy
                if targetAnt and targetAnt.player == playerId:
                    targetAnt = None

                if targetAnt:
                    targetAnt.health -= UNIT_STATS[ant.type][ATTACK]
                    # remove from board if enemy is killed
                    if targetAnt.health < 1:
                        futureState.inventories[enemyId].ants.remove(targetAnt)
                    continue

        return futureState
示例#13
0
    Ant((0, 0), QUEEN, PLAYER_ONE)
], [
    Building((2, 2), ANTHILL, PLAYER_ONE),
    Building((3, 4), TUNNEL, PLAYER_ONE)
], 1)
inventory2 = Inventory(PLAYER_TWO, [
    Ant((0, 9), SOLDIER, PLAYER_TWO),
    Ant((1, 9), WORKER, PLAYER_TWO),
    Ant((7, 2), WORKER, PLAYER_TWO),
    Ant((9, 9), QUEEN, PLAYER_TWO)
], [
    Building((8, 8), ANTHILL, PLAYER_TWO),
    Building((2, 8), TUNNEL, PLAYER_TWO)
], 1)
inventory3 = Inventory(
    NEUTRAL, [], [Construction((9, 6), GRASS),
                  Construction((4, 0), FOOD)], 0)
test1InitState = GameState(None, (inventory1, inventory2, inventory3),
                           PLAY_PHASE, PLAYER_ONE)

# evaluate the initial board
eval1 = aiPlayer.evaluateState(test1InitState)

testMoveBuildDrone = Move(BUILD, [(8, 3)], DRONE)
futureState = aiPlayer.getFutureState(test1InitState, testMoveBuildDrone)

# verify that the future state is correct
droneExists = False
for ant in futureState.inventories[PLAYER_ONE].ants:
    if ant.type == DRONE and ant.coords == (8, 3):
        droneExists = True