# Tony Curnes
# CIS Senior Design
# An Analysis of Trade on Complex Networks
# Module : MW.py

import copy, random, numpy, time, sys, pickle, hippo
from Evaluator import *

def bucketWealth(wealth):
    """
    Divides wealth into buckets
    """
    if wealth < 0.5:
        return 0
    elif wealth < 1:
        return 1
    elif wealth == 1:
        return 2
    else:
        return 3
    
def bucketCost(cost):
    """
    Divides cost into buckets
    """
    if cost < .1:
        return 0
    elif cost < .3:
        return 1
    else:
        return 2
    
def bucketNeighbor(wealth):
    """
    Divides wealth into buckets which
    are less specific as above.
    """
    if wealth < 0:
        return 3
    elif wealth < 1:
        return 0
    elif wealth == 1:
        return 1
    else:
        return 2

def socialFn(stDev):
    """
    Predicts the average social welfare of a graph based on 
    the standard deviation of wealth that is present in the
    graph.  The prediction is derived from actual data
    collected during the 2007 Milks and Wheats experiment
    run by Profs. Kearns and Judd.  The prediction is determined
    through a linear regression, although a quadratic formula
    may be used if one substitutes in 2 for degree.
    """
    stdAcqOverAvgAcq = numpy.array([.036,.26,.29,.28,.08,.12,.26,
                                    .60,.76,.66,.48,.32,.66,
                                    .20,.17,.27,.34,.24,.48,
                                    .11,.11,.19,.93,.68,1.8,
                                    .25,.24,.30])
    avgAcq = numpy.array([.99,.87,.88,.88,.96,.96,.92,.71,.77,.76,
                          .82,.92,.91,.94,.95,.92,.85,.93,.90,
                          .96,.97,.93,.67,.73,.77,.91,.93,.87])
    stdAcq = stdAcqOverAvgAcq * avgAcq
    degree = 1
    fittedCurve = numpy.polyfit(stdAcq, avgAcq, degree)
    #print fittedCurve
    result = 0
    for x in range(degree + 1):
        result += (fittedCurve[x] * (stDev**(degree-x)))
    return result

def debug(myClass):
    """
    Debug switch, if 1 it will print out debug statements
    in the class which this function is called upon,  
    if 0 it will not print these out
    
    Set to 0 once finished using.
    """
    debug_search = 0
    debug_eval = 0
    debug_learner = 0
    debug_heur = 0
    if isinstance(myClass, SearchAgent):
        return debug_search
    elif isinstance(myClass, HeuristicAgent):
        return debug_heur
    elif isinstance(myClass, Evaluator):
        return debug_eval
    elif isinstance(myClass, QLearner):
        return debug_learner
    
def getDegInfo(neighborInfo):
    """
    Given neighbor info on a particular player, 
    returns a tuple of (maxDeg, minDeg)
    """
    maxDeg = 0
    minDeg = 1000
    for elem in neighborInfo:
        if maxDeg < elem[1]:
            maxDeg = elem[1]
        if minDeg > elem[1]:
            minDeg = elem[1]
    return (maxDeg, minDeg)
    
def convertDecisionList(decision):
    """
    Takes a list of players' decisions (which currently contain
    references to players) and converts them into numbers
    """
    for elem in range(len(decision)):
        if decision[elem] != None:
            conv = []
            for x in decision[elem]:
                if x != None:
                    conv.append(x.num)
            decision[elem] = conv
    return decision

def powerSet(inputSet):
    """
    This method finds the power set of an input set
    by representing each element of the power set as
    a binary number based on the element's index.
    Which elements from the input set to include in
    each element of the power set is then determined
    by bitwise-anding.  This is a helper function for
    getArgMax as well as decidePurchase
    """
    powerSet = []
    for x in range(2**len(inputSet)):
        subSet = []
        for elem in range(len(inputSet)):
            if x & 2**elem:
                subSet.append(inputSet[elem])
        powerSet.append(subSet)
    return powerSet

def getArgMax(network, milksLeft, wheatsLeft):
    """
    This method looks at all possible sets of milk vertices
    and finds the one with the highest ratio of milk vertices
    to connected wheat vertices.  This is a helper function for
    the equilibrium algorithm.
    """
    milkSets = powerSet(milksLeft)
    bestRatio = 0
    bestSet = None
    for milkSet in milkSets:
        wheatSet = []
        for elem in milkSet:
            for x in range(len(network[elem])):
                if network[elem][x] == 1 and x in wheatsLeft and x not in wheatSet:
                    wheatSet.append(x)
        if len(wheatSet) != 0:
            ratio = float(len(milkSet))/float(len(wheatSet))
        else:
            ratio = 0
        if ratio > bestRatio:
            bestRatio = ratio
            bestSet = (milkSet,wheatSet)
    return bestSet
    
def generateNetwork(size,type):
    """
    This method generates a random network based on some generative
    model.  Currently it supports four models.  First is perfect matching,
    where the variation in equilibrium wealth is zero.  Second is a clan graph,
    where there are four different neighborhoods that are relatively isolated
    and then a few powerful vertices that connect those neighborhoods to the
    entire graph.  Third is the preferential attachment tree model, where there is
    high variation in equilibrium wealth.  Finally is the dense preferential attachment
    model, with low variation in equilibrium wealth.  Please refer to my paper
    on this network for more information about these network structures.
    """
    if size % 2 == 1:
        print "Error: network should have even number of vertices."
        return None
    networkCols = [0]*size
    network = []
    for x in range(size):
        network.append(copy.copy(networkCols))
    if type == "pr":
        #perfect matching
        for x in range(size/2):
            network[x][x+size/2] = 1
            network[x+size/2][x] = 1
    elif type == "cln0":
        #clan graph with no rewiring
        if size % 18 != 0:
            print "Error: clan graphs must have 36 vertices."
            return None
        for x in range(size/2):
            network[x][34] = 1
            network[34][x] = 1
            network[x][35] = 1
            network[35][x] = 1
            if x in range(2):
                for y in range(6):
                    network[x][18+y] = 1
                    network[18+y][x] = 1
            elif x in range(2,8):
                for y in range(2):
                    network[x][24+y] = 1
                    network[24+y][x] = 1
            elif x in range(8,10):
                for y in range(6):
                    network[x][26+y] = 1
                    network[26+y][x] = 1
            elif x in range(10,16):
                for y in range(2):
                    network[x][32+y] = 1
                    network[32+y][x] = 1
            else:
                for y in range(18):
                    network[x][18+y] = 1
                    network[18+y][x] = 1
    elif type == "pa1":
        # alternate adding milks and wheats to tree, one edge apiece
        milkList = []
        wheatList = []
        for x in range(size/2):
            if x == 0:
                network[0][size/2] = 1
                network[size/2][0] = 1
                milkList.append(0)
                wheatList.append(size/2)
            else:
                milkChoice = random.choice(milkList)
                wheatChoice = random.choice(wheatList)
                milkList.append(milkChoice)
                milkList.append(x)
                wheatList.append(wheatChoice)
                wheatList.append(x+size/2)
                network[x][wheatChoice] = 1
                network[wheatChoice][x] = 1
                network[x+size/2][milkChoice] = 1
                network[milkChoice][x+size/2] = 1
    elif type == "pa2":
        # alternate adding milks and wheats to graph, two edges apiece
        milkList = []
        wheatList = []
        for x in range(size/2):
            if x == 0:
                network[0][size/2] = 1
                network[size/2][0] = 1
                milkList.append(0)
                wheatList.append(size/2)
            elif x == 1:
                network[1][size/2] = 1
                network[size/2][1] = 1
                network[0][size/2+1] = 1
                network[size/2+1][0] = 1
                milkList.extend([0,1])
                wheatList.extend([size/2,size/2+1])
            else:
                milkChoice = random.choice(milkList)
                wheatChoice1 = random.choice(wheatList)
                wheatChoice2 = random.choice(wheatList)
                while wheatChoice2 == wheatChoice1:
                    wheatChoice2 = random.choice(wheatList)
                milkList.extend([milkChoice,x,x])
                wheatList.extend([wheatChoice1,wheatChoice2,x+size/2])
                network[x][wheatChoice1] = 1
                network[wheatChoice1][x] = 1
                network[x][wheatChoice2] = 1
                network[wheatChoice2][x] = 1
                network[x+size/2][milkChoice] = 1
                network[milkChoice][x+size/2] = 1
    elif (type == "cyc2"):
        for x in range(size/2):
            network[x][x+size/2] = 1
            network[x+size/2][x] = 1
            if x < (size/2 - 1):
                network[x][x+size/2+1] = 1
                network[x+size/2+1][x] = 1
            else:
                network[size/2-1][size/2] = 1
                network[size/2][size/2-1] = 1
    else:
        return "None"
    return network

class Game:
    """
    This class keeps track of the state of the game as well as operates it,
    asking for input from the players when necessary.
    """
    def __init__(self, size, type, agent, cost=0.02, maxBuys=2, network=None, steps=3):
        """
        Initializes a game, instantiating various variables to keep track of the
        state of the game as well as record statistics about the game.
        """
        self.stage = 0
        self.players = []
        # you can either have the program generate a network
        # for you or input your own
        if network == None:
            self.network = generateNetwork(size,type)
        else:
            self.network = network
        #self.initNetwork = copy.copy(network)
        self.agent = agent
        self.cost = cost
        self.steps = steps
        self.maxBuys = maxBuys
        self.numPlayers = len(self.network)
        for x in range(self.numPlayers):
            self.players.append(Player(x, self, agent))
        self.stageWealths = [self.getEqWealths()]
        self.moneySpent = 0
        self.connections = []
        # Below, update player's info about themselves
        for elem in self.players:
            elem.initDegree = elem.getNumNeighbors()
            elem.initNeighborInfo = elem.getNeighborInfo()
            elem.possInfo = elem.possPurchaseInfo() # copy this?
    
    def play(self):
        """
        After a game is instantiated, it may be run by calling this function,
        which plays each stage in turn.  For a one-stage game, the function
        is not strictly necessary, but I kept it around to preserve flexibility.
        """
        while self.stage < 1: 
            self.playStage()
        
    def getAvgWealth(self):
        """
        This returns the average wealth of all players as a single number 
        after the game is finished; it is one measure of how efficiently 
        players purchased edges.  Note that the game itself may cause
        negative social utility since players may make decisions that
        are only slightly beneficial to themselves while being largely
        detrimental to their neighbors
        """
        totalWealth = []
        for x in range(self.numPlayers):
            totalWealth.append(0)
            for stage in self.stageWealths:
                totalWealth[x] += stage[x]
        stages = self.stage + 1
        avgWealth = [x/stages for x in totalWealth]
        return avgWealth
    
    def getStDevWealth(self,stage):
        """
        This returns the standard deviation of wealth in the graph for
        a particular stage and is a measure of the equality of the graph.
        """
        if stage >= len(self.stageWealths):
            return "Error"
        else:
            stageWealth = self.stageWealths[stage]
            a = numpy.array(stageWealth)
            return numpy.std(a)
    
    def playStage(self):
        """
        This plays a particular stage of the game, prompting
        vertices for their buying decisions and then calculating
        equilibrium wealth
        """
        # prompt all milks for their buying decisions
        decision = []
        if not isinstance(self.agent, QLearner):
            self.agent.getAllMoves()
        for x in range(self.numPlayers/2):
            decision.append(self.players[x].decidePurchase())
        decision = convertDecisionList(decision)
        for x in range(self.numPlayers/2):
            if decision[x]:
                for elem in decision[x]:
                    # for each element in the decision list
                    # add edge to network, and deduct wealth from player
                    num = self.players[x].num
                    self.network[num][elem] = 1
                    self.network[elem][num] = 1
                    self.stageWealths[self.stage][num]
                    self.moneySpent += self.cost
                    if self.moneySpent > self.cost * self.numPlayers:
                        print "exceeded max spend"
                    self.connections.append(self.players[elem]) # only works for 2-stage game
            else:
                self.connections.append(None) # indicates no connection
        self.stage += 1
        self.stageWealths.append(self.getEqWealths())
        
    def gameStats(self):
        """
        Returns a number of stats about the game, specifically:
        Aggregate increase in social wealth, aggregate money spent
        Edge cost, size of network, and x player info lists, where
        x is number of players in the network
        Each player info list in turn
        """
        # aggregate stats
        # edgesBought = self.moneySpent / self.cost
        if self.stage != 1:
            print "Game has not been played yet!"
            sys.exit(0)
        gameStats = []
        stdBeg = self.getStDevWealth(0)
        stdEnd = self.getStDevWealth(1)
        wealthInc = socialFn(stdEnd) - socialFn(stdBeg)
        gameStats.append(wealthInc*self.numPlayers)
        gameStats.append(self.moneySpent)
        gameStats.append(self.cost)
        gameStats.append(len(self.network))
        # individual player stats
        for player in self.players:
            playerStats = []
            # things to return, all in a separate list
            playerStats.append(player.num)
            playerStats.append(self.stageWealths[0][player.num])
            playerStats.append(self.stageWealths[1][player.num])
            playerStats.append(player.predUtil)
            playerStats.append(player.initDegree)
            playerStats.append(player.numEdgesPurchased)
            if player.edgesPurchasedList == None:
                playerStats.append(None)
            else:
                playerStats.append([elem.num for elem in player.edgesPurchasedList])
            playerStats.append(player.getPurchaseInfo())
            playerStats.append(player.postPurchaseInfo())
            playerStats.append(player.possInfo)
            gameStats.append(copy.copy(playerStats))
        return gameStats
            
    def getEqWealths(self):
        """
        Returns the equilibrium wealths for a network, using the algorithm
        outlined in "A network formation game for bipartite exchange
        economies" by Even-Dar et. al.  The algorithm is not the most
        efficient existing one to compute the equilibrium but will serve
        well for our purposes.
        """
        network = self.network
        milksLeft = range(len(network)/2)
        wheatsLeft = range(len(network)/2)
        wealths = range(len(network))
        wheatsLeft = [elem + len(network)/2 for elem in wheatsLeft]
        while len(milksLeft) != 0:
            c = getArgMax(network,milksLeft,wheatsLeft)
            for elem in c[0]:
                if elem in milksLeft:
                    milksLeft.remove(elem)
                    wealths[elem] = float(len(c[1])) / float(len(c[0]))
            for elem in c[1]:
                if elem in wheatsLeft:
                    wheatsLeft.remove(elem)
                    wealths[elem] = float(len(c[0])) / float(len(c[1]))
        for elem in wealths:
            if elem < 0:
                print "!!"
        return wealths
    
    def wealthBalanced(self):
        """
        Returns true if everyone has the same equilibrium wealth,
        otherwise false
        """
        wealths = self.getEqWealths()
        for elem in wealths:
            if elem != 1:
                return False
        return True
    
    def getNumEdges(self):
        """
        Returns the number of edges in the network, really counting each
        edge as two - one in one direction and one in the other direction
        """
        num = 0
        for x in range(len(self.network)):
            for y in range(len(self.network)):
                if self.network[x][y] == 1:
                    num += 1
        return num
        
class Player:
    """
    This implements the player class, whose main function is deciding
    which edges to purchase in order to maximize wealth
    """
    def __init__(self, num, game, agent):
        """
        Instantiates an instance of the player class
        """
        self.num = num
        self.endowment = 1
        self.wealth = 0
        self.totWealth = 0
        self.game = game
        self.agent = agent
        self.initDegree = 0
        self.initNeighborInfo = 0
        self.numEdgesPurchased = 0
        self.avgDegEdgesPurchased = 0
        self.edgesPurchasedList = None
        self.possInfo = None
        # only for buyers (milks)
        self.predUtil = 0
        
    def getType(self):
        """
        Returns which type of vertex the player is, milk or wheat
        """
        if self.num < len(self.game.network)/2:
            return "Milk"
        else:
            return "Wheat"
        
    def rewardFn(self):
        """
        Returns the total reward experienced by a player during
        a game.  The reward is measured as the incremental gain
        (or loss) in equilibrium wealth, minus the amount spent
        by the player on edge purchases
        """
        begWealth = self.game.stageWealths[0][self.num]
        spent = self.numEdgesPurchased * self.game.cost
        if len(self.game.stageWealths) > 1:
            endWealth = self.game.stageWealths[1][self.num]
        else:
            endWealth = self.game.getEqWealths()[self.num]
        return (endWealth - spent - begWealth)
        
    def getPrevRoundWealth(self):
        """
        Returns your equilibrium wealth in the 0th round
        """
        return self.game.stageWealths[0][self.num]
        
    def getNeighbors(self):
        """
        Returns a list containing references to all neighbors
        of the current vertex
        """
        neighbors = []
        for x in range(self.game.numPlayers):
            if self.game.network[self.num][x] == 1:
                neighbors.append(self.game.players[x])
        return neighbors
    
    def getNumNeighbors(self):
        """
        Returns the number of neighbors the vertex has
        """
        neighbors = self.getNeighbors()
        return len(neighbors)
    
    def getNeighborInfo(self):
        """
        returns a list which contains tuples representing
        each of your neighbors.  The tuple is 
        (neighbor ID, neighbor degree)
        """
        neighborInfo = []
        for elem in range(len(self.game.network[self.num])):
            if self.game.network[self.num][elem] == 1:
                neighborInfo.append((elem,self.game.players[elem].getNumNeighbors()))
        return neighborInfo
    
    def getEligiblePurchases(self, steps):
        """
        This returns all vertices the player is eligible to purchase
        In order to be able to purchase a vertex, you have to be in 
        its neighborhood, defined to be three hops away.
        
        This method has been updated to accept any number of 
        (odd) steps away
        """
        if steps % 2 == 0:
            print "Error: number of steps should be even"
            return None
        oneStep = self.getNeighbors()
        evenStep = []
        oddStep = copy.copy(oneStep)
        for x in range(steps - 1):
            if x % 2 == 0:
                for player in oddStep:
                    evenStep.extend(player.getNeighbors())
            else:
                for player in evenStep:
                    oddStep.extend(player.getNeighbors())
        # removes duplicates and players you are already connected to
        oddStep = [elem.num for elem in oddStep]
        oddStep = list(set(oddStep))
        for player in oneStep:
            if player.num in oddStep:
                oddStep.remove(player.num)
        oddStep = [self.game.players[elem] for elem in oddStep]
        return oddStep
    
    def possPurchaseInfo(self):
        """
        Exactly like get purchase info, but for information about the
        possible purchases the player can make instead of information
        about the actual purchases the player is making.
        """
        poss = self.getEligiblePurchases(self.game.steps)
        equilList = []
        for player in poss:
            equilList.append(player.getPrevRoundWealth())
        equilList = sorted(equilList)
        return equilList
    
    def getPurchaseInfo(self):
        """
        This is a helper method to getDelta in the QLearner class,
        it takes the purchase info that the decidePurchase method
        generates and sorts it so that it can be used by getDelta.
        """
        if self.edgesPurchasedList == None:
            return None
        else:
            equilList = [edge.getPrevRoundWealth() for edge in
                         self.edgesPurchasedList]
            # sorts from bottom up
            equilList = sorted(equilList)
            return equilList
        
    def postPurchaseInfo(self):
        """
        This is a helper method to gameStats that returns info
        about how the edges that got purchased to fared after
        the round was over
        """
        if self.game.stage != 1:
            print "Error, game has not been played yet!"
            # maybe use exception here??
            sys.exit(0)
        if self.edgesPurchasedList == None:
            return None
        else:
            # check on this to make sure
            equilList = [edge.game.stageWealths[1][edge.num] for edge in
                         self.edgesPurchasedList]
            # sorts from bottom up
            equilList = sorted(equilList)
            return equilList
    
    def decidePurchase(self):
        """
        This function is at the core of the program, as it returns
        a list of bought edges or None.  It uses a variety of AI algorithms
        to decide which purchase it should make, corresponding to each
        of the agent classes below
        """
        if isinstance(self.agent,QLearner):
            poss = self.getEligiblePurchases(self.game.steps)
            maxUtil = self.agent.evalFn(self)
            bestStrat = None
            if len(poss) > 0:
                # for each combination of choices, examine the utility of that choice
                # then pick the best utility
                possPurchases = powerSet(poss)
                possPurchases = [x for x in possPurchases if len(x) > 0 and len(x) <= self.game.maxBuys]
                for purchase in possPurchases:
                    # each elem is a list containing some number of players
                    self.numEdgesPurchased = len(purchase)
                    totDegree = 0.0
                    for edge in purchase:
                        totDegree += edge.getNumNeighbors()
                    self.avgDegEdgesPurchased = totDegree / len(purchase)
                    self.edgesPurchasedList = purchase
                    util = self.agent.evalFn(self)
                    if util > maxUtil:
                        maxUtil = util
                        bestStrat = purchase
                if random.random() < self.agent.exploreFrac:
                    # just pick a random possible purchase
                    possPurchases.append(None)
                    bestStrat = random.choice(possPurchases)
                if bestStrat == None:
                    self.numEdgesPurchased = 0
                    self.avgDegEdgesPurchased = 0
                    self.edgesPurchasedList = None
                else:
                    self.numEdgesPurchased = len(bestStrat)
                    totDegree = 0.0
                    for edge in bestStrat:
                        totDegree += edge.getNumNeighbors()
                    self.avgDegEdgesPurchased = totDegree / len(bestStrat)
                    self.edgesPurchasedList = bestStrat
                return bestStrat
            else:
                self.numEdgesPurchased = 0
                self.avgDegEdgesPurchased = 0
                return None
        else:
            move = self.agent.getMove(self)[1]
            # update stats and return move
            if move == None:
                self.numEdgesPurchased = 0
                self.avgDegEdgesPurchased = 0.0
                self.edgesPurchasedList = move
            else:
                self.numEdgesPurchased = len(move)
                totDegree = 0.0
                for edge in move:
                    totDegree += edge.getNumNeighbors()
                self.avgDegEdgesPurchased = totDegree / len(move)
                self.edgesPurchasedList = move
            return move
        
class Agent:
    """
    This is the superclass for all three agents, the searcher,
    learner, and heuristic agent.  It contains generic functions
    and variables common to all three
    """
    def __init__(self, gameSize, networks = None):
        """
        Initializes a new agent
        """
        self.gameSize = gameSize
        self.game = None
        # list of the best purchases for each player, developed by
        # getAllMoves and correctly sorted
        self.optMoves = []
        self.gameStats = []
        self.networks = networks
        
    def runAgent(self, trials):
        """
        Runs an agent for a specified number of trials by creating
        a new game for each trial, running the game with the designated agent
        making the decisions for the players, and collecting stats about
        the trials that were executed.  The networks the trials were run on
        are returned at the end of the method, so that other tests may use
        the same networks for consistency.
        """
        newNetworks = []
        for x in range(trials):
            cost = (.1) * (x % 10) + .05
            if self.networks:
                # need to default
                self.game = Game(len(self.networks[x]), "pa1", self, network = self.networks[x], cost = cost)
            else:
                self.game = Game(self.gameSize, "pa1", self, cost = cost)
                newNetworks.append(copy.deepcopy(self.game.network))
            self.game.play()
            self.gameStats.append(self.game.gameStats())
            #print "Game Run, size " + str(len(self.networks[x]))
            #if debug(self):
            #print "Game Run, size " + str(self.gameSize)
            #print x
        return newNetworks
            
    def getMove(self, player):
        """
        Since the agents determine all of the moves before they are
        actually made by the players, this function simply looks up
        the move that the agent has determined the player should
        make and returns it.
        """
        return self.optMoves[player.num]
        
class SearchAgent(Agent):
    """
    This class has no learning curve, it just evaluates situations
    using a search tree.  The algorithm is an analog of minimax,
    using adaptations for computational efficiency and the fact
    that the game we are playing is not zero-sum
    
    Unfortunately, can't implement abp in this situation because 
    the game is not zero-sum; this limitation is discussed more
    in the writeup
    """
            
    def getAllMoves(self):
        """
        With one evaluation of the search tree, this function
        determines the moves for each player in the game.
        The order of the searching is randomized to ensure that
        no player is automatically favored over another based on
        his positioning in the player list.
        """
        # randomize list
        order = range(self.game.numPlayers / 2)
        random.shuffle(order)
        depth = 0
        optList = self.recursiveSearch(order, depth)
        optList.sort()
        self.optMoves = optList
        
    def recursiveSearch(self, order, depth):
        """
        This is the heart of the search algorithm.  Like most search algorithms
        on games, the algorithm tries out a move and then recursively calls the function
        to see what happens further down the search tree.  It then undoes the move
        and tries another move, eventually picking the move that leads to the best outcome
        for the player represented by that level.  The method chooses not to copy the game
        and feed it in, instead undoing moves as the function returns; this method is a
        more complex and led to some debugging issues but saves time computationally and
        memory-wise.
        """
        player = self.game.players[order[depth]]
        poss = player.getEligiblePurchases(player.game.steps)
        possPurchases = powerSet(poss)
        possPurchases = [x for x in possPurchases if len(x) > 0 and len(x) <= self.game.maxBuys]
        possPurchases.append(None)
        bestStrat = []
        maxReward = -1000
        optList = []
        for purchase in possPurchases:
            if purchase != None:
                player.numEdgesPurchased = len(purchase)
                # indicator setting
                player.avgDegEdgesPurchased = -1
                for elem in purchase:
                    # add link to board
                    if debug(self):
                        print "Player " + str(player.num) + " tried edge " + str(elem.num)
                    self.game.network[order[depth]][elem.num] = 1
                    self.game.network[elem.num][order[depth]] = 1
            # call recursive search to get returned board
            if depth != self.game.numPlayers/2 - 1:
                moveList = self.recursiveSearch(order, depth+1)
            else:
                moveList = []
            # update best move
            reward = player.rewardFn()
            if reward > maxReward:
                maxReward = reward
                bestStrat = purchase
                optList = moveList
            # clear board for next loop
            if purchase != None:
                for elem in purchase:
                    if debug(self):
                        print "Player " + str(player.num) + " removed edge " + str(elem.num)
                    self.game.network[order[depth]][elem.num] = 0
                    self.game.network[elem.num][order[depth]] = 0
            # clear old optList
            for decision in moveList:
                strat = decision[1]
                if strat != None:
                    for elem in strat:
                        if debug(self):
                            print "Player " + str(player.num) + " removed edge " + str(elem.num)
                        self.game.network[decision[0]][elem.num] = 0
                        self.game.network[elem.num][decision[0]] = 0
        # modify board to contain the best possibility
        if bestStrat != None:
            player.numEdgesPurchased = len(bestStrat)
            player.avgDegEdgesPurchased = -1
            for elem in bestStrat:
                if debug(self):
                    print "Player " + str(player.num) + " tried edge " + str(elem.num)
                self.game.network[order[depth]][elem.num] = 1
                self.game.network[elem.num][order[depth]] = 1
            for decision in optList:
                strat = decision[1]
                if strat != None:
                    for elem in strat:
                        if debug(self):
                            print "Player " + str(player.num) + " tried edge " + str(elem.num)
                        self.game.network[decision[0]][elem.num] = 1
                        self.game.network[elem.num][decision[0]] = 1
        optList.append((player.num, bestStrat))
        return optList
    
class HeuristicAgent(Agent):
    """
    This agent is based off of the results from the learning agent, it is
    essentially the strategy of the learning agent in a boiled down form, so
    that a human player could remember and use the strategy; thus, the
    heuristic nature of the strategy.  The strategy itself is explained
    in my project write-up
    """
    
    def getAllMoves(self):
        """
        This function gets all of the moves for each player simultaneously
        by calling getMoveHelper, which applies the heuristic that
        we have developed
        """
        optList = []
        for x in range(self.game.numPlayers / 2):
            optList.append([x,self.getMoveHelper(self.game.players[x])])
        self.optMoves = optList
    
    def getMoveHelper(self, player):
        """
        This function divides a player's situation up into
        'buckets' and then makes a buying decision based on which
        buckets the player falls into.  The heuristic is 
        relatively simple and is designed so that a player
        playing this game during a behavioral experiment
        could remember it.
        """
        possInfo = player.possInfo
        b1 = bucketWealth(player.getPrevRoundWealth())
        b2 = bucketWealth(player.game.cost)
        if len(possInfo) > 0:
            b3 = bucketNeighbor(possInfo[0])
        else:
            b3 = bucketNeighbor(-1)
        # implement heuristic based on b's
        # to buy an edge, get poss purchases and then
        # match with possInfo's information about equil
        possPurchases = player.getEligiblePurchases(player.game.steps)
        firstPurchase = None
        secondPurchase = None
        if len(possInfo) == 0:
            return None
        elif len(possInfo) >= 1:
            for elem in possPurchases:
                if elem.getPrevRoundWealth() == possInfo[0]:
                    firstPurchase = elem
                    continue
        if len(possInfo) > 1:
            for elem in possPurchases:
                if elem.getPrevRoundWealth() == possInfo[1]:
                    secondPurchase = elem
                    continue
        # once you know your possible purchases, decide whether to buy
        purchase = []
        if len(possInfo) == 0:
            return None
        if b2 <= 1:
            purchase.append(firstPurchase)
            if len(possInfo) == 2:
                purchase.append(secondPurchase)
        else:
            if b1 < 1:
                purchase.append(firstPurchase)
            elif b3 < 1:
                # buy if b3 == 0
                purchase.append(firstPurchase)
            else:
                return None
        return purchase
        
class QLearner(Agent):
    
    """
    The QLearner runs various simulations in order to 
    come up with an evaluation function
    
    It then lends this evaluation function to players in order
    to help them make buying decisions
    """
    def __init__(self, gameSize, useFile = 1,
                 exploreFrac=0.50, networks = None):
        """
        Initializes a new QLearning agent, all it has to remember are the
        parameters that it uses to evaluate the utility of various situations
        """
        self.gameSize = gameSize
        self.exploreFrac = exploreFrac
        self.initialexploreFrac = exploreFrac
        self.alphaVal = 0.0005
        self.maxChange = 0.0005
        self.trial = 0
        self.performance = []
        # this is a list of the game stats, with the list index corresponding
        # to the trial
        self.gameStats = []
        self.game = None
        self.networks = networks
        self.numParams = 17
        self.cost = 0
        self.useFile = useFile
        
        # parameter setups
        self.params = numpy.zeros(self.numParams)
        self.paramSwitches = numpy.ones(self.numParams)
        if self.useFile:
            myfile = file("params", "r")
            self.params = pickle.load(myfile)
            myfile.close()
            myfile = file("paramSwitches", "r")
            self.paramSwitches = pickle.load(myfile)
            myfile.close()
            
    def evalAlpha(self, rawChange):
        """
        This function represents the amount by which the
        coefficients for the evaluation function can change with
        each iteration.  There is a maxChange value so the
        coefficients do not start to swing too wildly.
        """
        change = rawChange * self.alphaVal
        if change < 0:
            return max(change,-self.maxChange)
        else:
            return min(change, self.maxChange)
        
    def measurePerformance(self):
        """
        This looks at all the trials that were run by the learner
        and then returns the average performance of the learner
        over all those trials.  The first returned number in the
        list is the average absolute error, whereas the second is
        simply the summed error (measures if there is skew or if
        the error is unbiased)
        """
        measure = 0.0
        measure2 = 0.0
        # each elem represents the experience of a single
        # player
        for elem in self.performance:
            measure += abs(elem[0] - elem[1])
            measure2 += elem[0] - elem[1]
        trials = len(self.performance)
        return [measure / trials, measure2 / trials]
    
    def adjustSkew(self, skew):
        """
        This function adjusts for the skew observed in the
        evaluation function after it has been tested.  By skew
        we mean the tendency of the evaluation function to
        consistently underestimate or overestimate the rewards.
        To do this, you just need to adjust the intercept, 
        represented by the first parameter
        
        This is deprecated, skew was simply a function of not
        running the evaluation function developer enough times
        """
        # negative skew means you're underestimating rewards, so you
        # would want to add; and vice versa
        adj = -skew
        self.params[0] += adj
    
    def getDelta(self, player, num):
        """
        This is a helper to the Widrow-Huff formula, 
        given a parameter number and a player it determines
        a multiple related to how much the evaluation
        parameter under evaluation should change by.  It
        is also used by the evaluation function itself.
        
        For instance, if a player has 2 neighbors and the 
        switch for the neighbor parameter is set to 2, then
        the function should multiply the change by 4
        """
        delta = 0
        equilList = player.getPurchaseInfo()
        if num == 0:
            # base coefficient
            delta = 1
        if player.numEdgesPurchased == 1:
            if num == 1:
                # base coefficient
                delta = 1
            elif num == 2:
                # inverse of wealth
                delta = 1.0 / player.game.stageWealths[0][player.num]
            elif num == 3:
                # inverse of wealth of poorest bought edge
                delta = 1.0 / equilList[0]
            elif num == 4:
                # interactions
                delta = 1.0 / (player.game.stageWealths[0][player.num] * 
                               equilList[0])
            elif num == 5:
                # degree
                delta = player.getNumNeighbors()
            elif num == 6:
                # edge cost
                delta = player.game.cost
            elif num == 7:
                # normalized game size
                delta = player.game.numPlayers / 16.0
            elif num == 8:
                # std dev of game
                delta = player.game.getStDevWealth(0)
        elif player.numEdgesPurchased == 2:
            if num == 9:
                # base coefficient
                delta = 1
            elif num == 10:
                # inverse of wealth (will it work with reg?)
                delta = 1.0 / player.game.stageWealths[0][player.num]
            elif num == 11:
                # inverse of wealth of poorest bought edge
                delta = 1.0 / equilList[0]
            elif num == 12:
                # interactions
                delta = 1.0 / (player.game.stageWealths[0][player.num] * 
                               equilList[0])
            elif num == 13:
                # degree
                delta = player.getNumNeighbors()
            elif num == 14:
                # edge cost
                delta = player.game.cost
            elif num == 15:
                # normalized game size
                delta = player.game.numPlayers / 16.0
            elif num == 16:
                # std dev of game
                delta = player.game.getStDevWealth(0)
        return delta**int(self.paramSwitches[num])
    
    def evalFn(self, player):
        """
        This calculates the utility of a particular position
        by multiplying each parameter value by the delta
        and summing each value
        """
        utility = 0
        for x in range(self.numParams):
            utility += self.params[x] * self.getDelta(player, x)
        return utility
    
    def updateEvalFn(self, game):
        """
        Takes in a finished game as a parameter and updates the
        evaluation function accordingly, by going through each player
        and comparing the reward with the utility
        
        Rule for updating is as follows: param = param +
        alpha * (reward + discount * max utility of all poss. actions - curUtil)
        * partial derivative
        This is the Widrow-Hoff rule
        No discount factor since all moves are over a single time step
        """
        # only takes into account those players that actually bought
        for x in range(game.numPlayers/2):
            player = game.players[x]
            prevUtil = self.evalFn(player)
            #print "prevUtil: " + str(prevUtil)
            reward = player.rewardFn()
            #print "reward: " + str(reward)
            for y in range(self.numParams):
                rawChange = (reward - prevUtil) * self.getDelta(player, y)
                self.params[y] += self.evalAlpha(rawChange)
    
    def developEvalFn(self, trials):
        """
        This runs the QLearner for the inputted number of trials,
        the more trials run, the better it learns, updating the
        evaluation function using the Widrow-Hoff rule as it goes
        """
        self.exploreFrac = self.initialexploreFrac
        for x in range(trials):
            # set up game; last parameter is edgeCost, maxBuys if you want
            # ok, range 
            # decrement exploreFrac
            if x % (trials / 10) == 0:
                self.exploreFrac -= self.exploreFrac / 5
            self.trial = x
            # edge cost ranges between .05 and .95 and 
            # bumps up by .1 every trial
            self.cost = (.1) * (x % 10) + .05
            # network size ranges between 12 and 20 and
            # bumps up by 2 every 10 trials
            # this is so that every 50 trials has all the
            # combinations of edge costs and network sizes
            self.gameSize = 12 + 2 * ((x % 50) / 10)
            self.game = Game(self.gameSize, "pa1", self, cost=self.cost)
            self.game.play()
            self.updateEvalFn(self.game)
            if debug(self) and x == trials - 1:
                print "Final results:"
                print [round(elem,3) for elem in self.params]
                print self.exploreFrac

    def testEvalFn(self, trials, constCost = 0):
        """
        This simply sets the exploration fraction to zero
        and runs the learner, while not continuing to update
        the evaluation function.  Then, it gathers statistics
        from the running of the trials.  Thus, this measures
        the performance of the learner
        """
        newNetworks = []
        self.exploreFrac = 0
        self.gameStats = []
        self.performance = []
        for x in range(trials):
            # rotating parameters - see developEvalFn for explanation
            if not constCost:
                self.cost = (.1) * (x % 10) + .05
            # starting size was 12 but dropping to 6 for testing purposes
            # run 30 trials if you want to see 6, 8, 10; 20 otherwise
            self.gameSize = 12 + 2 * ((x % 50) / 10)
            if self.networks:
                # need to default
                self.game = Game(self.gameSize, "pa1", self, network = self.networks[x], cost=self.cost)
            else:
                self.game = Game(self.gameSize, "pa1", self, cost=self.cost)
                newNetworks.append(copy.deepcopy(self.game.network))
            self.game.play()
            for y in range(self.game.numPlayers/2):
                player = self.game.players[y]
                predUtil = self.evalFn(player)
                reward = player.rewardFn()
                player.predUtil = predUtil
                self.performance.append([predUtil, reward])
            self.gameStats.append(self.game.gameStats())
            if debug(self) and x % 500 == 0:
                print x
        return newNetworks
                
    def calibrateParams(self):
        """
        This function does the following in an iterative fashion
        It starts of with a certain set of switches, and then 
        develops an evalFn based on those switches for
        1000 trials.  Then, it will uses testEvalFn to determine the efficacy
        of the function.
        
        To make things simple, it tests each parameter separately
        At the end of the function, it sets paramSwitches
        to whatever calibrated setting it believes is best
        """
        self.paramSwitches = numpy.ones(self.numParams)
        best = numpy.ones(self.numParams)
        bestPerf = 0
        # balancing time vs. performance
        # doesn't need that much time to distinguish
        developTrials = 1000
        testTrials = 100
        for x in range(self.numParams):
            # can actually change this to whatever int you want
            for y in [0.5,1,2]:
                self.paramSwitches[x] = y
                self.developEvalFn(developTrials)
                self.testEvalFn(testTrials)
                perf = self.measurePerformance()[0]
                perf2 = self.measurePerformance()[1]
                if debug(self):
                    print "Performance on " + str(y) + " was " + str(perf)
                    print "Skew on " + str(y) + " was " + str(perf2)
                if y == 0.5 or perf < bestPerf:
                    bestPerf = perf
                    best[x] = y
                # back to defaults for next cycle
                self.performance = []
                self.gameStats = []
                self.paramSwitches[x] = 1
            if debug(self):
                print "Switch " + str(x) + " is " + str(best[x])
        self.paramSwitches = best
        if debug(self):
            print best
        
    def calibrateEdgeCosts(self):
        """
        This method calibrates the edge costs by doing the following - 
        starting edge cost at 0 and raising it incrementally until
        the aggregate money spent on edges equals the social wealth
        gained through edge purchasing.  This helps to answer
        a question that I pose in my write-up
        """
        cost = 0.0
        utils = []
        spends = []
        costStep = 0.005
        # balancing time vs. performance
        testTrials = 100
        # only need to run once since your function is
        # prepped for edgeCosts
        while (cost < 0.25):
            if debug(self):
                print "Cost is " + str(cost)
            self.cost = cost
            self.testEvalFn(testTrials, constCost = 1)
            stats = self.gameStats
            util = 0.0
            spent = 0.0
            for elem in stats:
                util += elem[0]
                spent += elem[1]
            utils.append(util / 300)
            spends.append(spent / 300)
            if debug(self):
                print "Util is " + str(util)
                print "Spent is " + str(spent)
            #if util > spent:
            cost += costStep
            #else:
            #    return cost
        if debug(self):
            for elem in utils:
                print elem
            for elem in spends:
                print elem
        return cost
                
