# Tony Curnes
# CIS Senior Design
# An Analysis of Trade on Complex Networks
# Module : Evaluator.py

from MW import *

class Evaluator:
    """
    This class compares the performance of the two agents,
    running various trials, saving the results of the trials
    to files, and then parsing the data in the files so that
    it may be interpreted.
    """
    def __init__(self):
        """
        Sets up a new Evaluator, you may change the three "Trials"
        numbers to run more or fewer trials on the functions that
        use those variables.
        """
        self.searcher = None
        self.learner = None
        self.gameSize = 16
        self.networks = []
        # number of trials the developEvalFn function will run for
        self.devTrials = 8000
        # number of trials the testEvalFn/other testers will run for
        self.testTrials = 5000
        # number of trials the data collector will run for
        self.collTrials = 500
        self.paramSwitches = numpy.ones(17)
        
    def evaluateEdgeCosts(self):
        """
        This function sets up a learner and calls the 
        function in it to calibrate the edge costs.  This function
        eventually prints out a number representing the edge cost
        which will balance aggregate money spent with aggregate
        social wealth gained from the execution of the game.
        """
        start = time.clock()
        self.learner = QLearner(self.gameSize)
        cost = self.learner.calibrateEdgeCosts()
        end = time.clock()
        if debug(self):
            print "Cost was " + str(cost)
            print "Edge cost took " + str(round((end - start), 1)) + " seconds."
        
    def evaluateParams(self):
        """
        This function sets up a clean learning agent and calibrates the
        degree of the parameters.  Each parameter can have degree 0.5, 1, 
        or 2, and since I had no indication of which one of these was best
        for each parameter I simply ran tests to figure it out.  The best
        degree for each parameter is saved in a text file and read in
        once the learner starts.
        """
        start = time.clock()
        paramSwitches = numpy.ones(17)
        self.learner = QLearner(self.gameSize, paramSwitches)
        self.learner.calibrateParams()
        self.paramSwitches = self.learner.paramSwitches
        end = time.clock()
        if debug(self):
            print "Params took " + str(round((end - start), 1)) + " seconds."
        
    def evaluateLearner(self):
        """
        This is a simple function to help evaluate the speed of the learning
        agent by running it for a set number of trials and seeing
        how long it took the agent to run.
        
        Additionally, earlier on in the debugging stage it was used
        for developing the evaluation function (which was accomplished
        simply by calling developEvalFn), it also printed out
        information about how the agent was performing.
        """
        start = time.clock()
        self.learner = QLearner(self.gameSize)
        #self.learner.developEvalFn(self.devTrials)
        self.networks = self.learner.testEvalFn(self.testTrials)
        end = time.clock()
        if debug(self) and (False):
            perf = self.learner.measurePerformance()[0]
            perf2 = self.learner.measurePerformance()[1]
            for x in range(49):
                # spent
                print self.learner.gameStats[x][1]
            print "Performance was " + str(perf)
            print "Skew was " + str(perf2)
            print numpy.atleast_1d(self.learner.params).tolist()
        print "Learner took " + str(round((end - start), 4)) + " seconds."
            
    def evaluateSearcher(self):
        """
        This is a simple function to help evaluate the speed of the search
        agent by running it for a set number of trials and seeing
        how long it took the agent to run.
        """
        start = time.clock()
        self.searcher = SearchAgent(self.gameSize, self.networks)
        self.searcher.runAgent(self.testTrials)
        end = time.clock()
        if debug(self):
            print "Searcher took " + str(round((end - start), 4)) + " seconds."
            
    def evaluateHeuristic(self):
        """
        This is a simple function to help evaluate the speed of the heuristic
        agent by running it for a set number of trials and seeing
        how long it took the agent to run.
        """
        start = time.clock()
        self.heur = HeuristicAgent(self.gameSize, self.networks)
        self.heur.runAgent(self.testTrials)
        end = time.clock()
        if debug(self):
            print "Heuristic took " + str(round((end - start), 4)) + " seconds."
        
            
    def compare(self):
        """
        This runs a comparison trial between the learning agent and the heuristic
        agent, collecting statistics from the running of trials by each agent and
        writing the statistics to files once the simulation is complete
        """
        self.evaluateLearner()
        #self.evaluateSearcher()
        self.evaluateHeuristic()
        learnerStats = self.learner.gameStats
        #searcherStats = self.searcher.gameStats
        heurStats = self.heur.gameStats
        #print len(searcherStats)
        myfile = file("learner.txt", "w")
        pickle.dump(learnerStats,myfile)
        myfile.close()
        myfile = file("heur.txt", "w")
        pickle.dump(heurStats,myfile)
        myfile.close()
        
    def parseCompareStats(self):
        """
        This reads in stats from the trials which compared
        the learning agent and the heuristic agent and prints
        out various results which are then turned into
        histograms off-program.
        """
        myfile = file("learner.txt", "r")
        learnerStats = pickle.load(myfile)
        myfile.close()
        myfile = file("heur.txt", "r")
        heurStats = pickle.load(myfile)
        myfile.close()
        # 5000 trials in each
        # separate performance based on network size
        # all lists are performance, trials
        # thus you can divide at the end and get your number
        # wealthInc = 0, cost = 2
        # moneySpent = 1, size = 3
        l12 = [0.0,0]
        l14 = [0.0,0]
        l16 = [0.0,0]
        l18 = [0.0,0]
        l20 = [0.0,0]
        h12 = [0.0,0]
        h14 = [0.0,0]
        h16 = [0.0,0]
        h18 = [0.0,0]
        h20 = [0.0,0]
        # 12, 14, 16, 18, 20
        for x in range(len(learnerStats)):
            lperf = learnerStats[x][0] - learnerStats[x][1]
            hperf = heurStats[x][0] - heurStats[x][1]
            if learnerStats[x][3] == 12:
                l12[0] += lperf
                l12[1] += 1
                h12[0] += hperf
                h12[1] += 1
            elif learnerStats[x][3] == 14:
                l14[0] += lperf
                l14[1] += 1
                h14[0] += hperf
                h14[1] += 1
            elif learnerStats[x][3] == 16:
                l16[0] += lperf
                l16[1] += 1
                h16[0] += hperf
                h16[1] += 1
            elif learnerStats[x][3] == 18:
                l18[0] += lperf
                l18[1] += 1
                h18[0] += hperf
                h18[1] += 1
            elif learnerStats[x][3] == 20:
                l20[0] += lperf
                l20[1] += 1
                h20[0] += hperf
                h20[1] += 1
        # learner followed by heur
        # this number represents the excess of 
        # money spent over total welfare gained
        # per trial
        print l12[0]/l12[1]
        print l14[0]/l14[1]
        print l16[0]/l16[1]
        print l18[0]/l18[1]
        print l20[0]/l20[1]
        print h12[0]/h12[1]
        print h14[0]/h14[1]
        print h16[0]/h16[1]
        print h18[0]/h18[1]
        print h20[0]/h20[1]
        # separate performance based on edge cost
        # < .1, < .3, <= 1
        l0 = [0.0,0]
        l1 = [0.0,0]
        l2 = [0.0,0]
        h0 = [0.0,0]
        h1 = [0.0,0]
        h2 = [0.0,0]
        for x in range(len(learnerStats)):
            lperf = learnerStats[x][0] - learnerStats[x][1]
            hperf = heurStats[x][0] - heurStats[x][1]
            if learnerStats[x][2] < 0.1:
                l0[0] += lperf
                l0[1] += 1
                h0[0] += hperf
                h0[1] += 1
            elif learnerStats[x][2] < 0.3:
                l1[0] += lperf
                l1[1] += 1
                h1[0] += hperf
                h1[1] += 1
            elif learnerStats[x][2] <= 1:
                l2[0] += lperf
                l2[1] += 1
                h2[0] += hperf
                h2[1] += 1
        # learner followed by heur
        print "next series"
        print l0[0]/l0[1]
        print l1[0]/l1[1]
        print l2[0]/l2[1]
        print h0[0]/h0[1]
        print h1[0]/h1[1]
        print h2[0]/h2[1]
            
    def collectLearnerStats(self):
        start = time.clock()
        self.learner = QLearner(self.gameSize)
        self.learner.testEvalFn(self.collTrials)
        perf = self.learner.performance
        stats = self.learner.gameStats
        myfile = file("perf.txt", "w")
        pickle.dump(perf,myfile)
        myfile.close()
        myfile = file("stats.txt", "w")
        pickle.dump(stats,myfile)
        myfile.close()
        # stats = pickle.load(myfile)
        end = time.clock()
        if debug(self):
            #print numpy.atleast_1d(self.learner.params).tolist()
            print "Collector took " + str(round((end - start), 1)) + " seconds."
            
    def bucketStats(self):
        """
        Takes the raw stats file, gameStats, and puts it into buckets
        based on the bucket helper functions at the beginning of MW.py
        These buckets are then used to help determine the heuristic
        agent's decisions.
        """
        myfile = file("stats.txt", "r")
        stats = pickle.load(myfile)
        myfile.close()
        # create a vector with multiple buckets
        # but how do you go from buckets to single list?
        # not a problem - just a lookup
        # here's your vector
        # 5, 4, 5, 5
        buckets = numpy.array([0])
        buckets = numpy.resize(buckets, (4,3,4,4,3))
        #right = numpy.atleast_1d(buckets[3][2][3][3]).tolist()
        for game in stats:
            cost = game[2]
            for elem in game:
                if isinstance(elem, list):
                    # then you know it is a player list
                    # extract necessary info for buckets
                    b1 = bucketWealth(elem[1])
                    b2 = bucketCost(cost)
                    possInfo = elem[9]
                    if len(possInfo) > 0:
                        b3 = bucketNeighbor(possInfo[0])
                    else:
                        b3 = bucketNeighbor(-1)
                    if len(possInfo) > 1:
                        b4 = bucketNeighbor(possInfo[1])
                    else:
                        b4 = bucketNeighbor(-1)
                    b5 = elem[5]
                    buckets[b1][b2][b3][b4][b5] += 1
        print buckets
        # after all info for buckets has been collected,
        # need to pick the most popular choice in each bucket
        newBuckets = numpy.array([0])
        newBuckets = numpy.resize(newBuckets, (4,3,4,4))
        for e1 in range(4):
            for e2 in range(3):
                for e3 in range(4):
                    for e4 in range(4):
                        best = buckets[e1][e2][e3][e4][0]
                        for e5 in range(3):
                            if buckets[e1][e2][e3][e4][e5] > best:
                                newBuckets[e1][e2][e3][e4] = e5
                                best = buckets[e1][e2][e3][e4][e5]
        myfile = file("buckets.txt", "w")
        pickle.dump(newBuckets,myfile)
        myfile.close()
        myfile = file("buckets.txt", "r")
        newBuckets = pickle.load(myfile)
        myfile.close()
        print newBuckets
        for e1 in range(4):
            for e2 in range(3):
                for e3 in range(4):
                    for e4 in range(4):
                        if newBuckets[e1][e2][e3][e4] == 1:
                            print [e1,e2,e3,e4]
                        elif newBuckets[e1][e2][e3][e4] == 2:
                            print "2:"
                            print [e1,e2,e3,e4]
            
    def graphStats(self):
        """
        This function takes in previously collected stats
        from a game, using the stats file.  It chops
        up the data using various subroutines and then
        graph them using hippodraw.
        """
        def bucketEdgesBought(stats):
            bucket = []
            for elem in stats:
                bucket.append(elem[5])
            return bucket
        def bucketWealthInc(stats):
            bucket = []
            for elem in stats:
                bucket.append(elem[2] - elem[1])
            return bucket
        myfile = file("perf.txt", "r")
        perf = pickle.load(myfile)
        myfile.close()
        switch = 1
        if switch == 0:
            wealthg2 = []
            wealthg1 = []
            wealth1 = []
            wealthl1 = []
            wealthl05 = []
            # go through all the player instances in 
            myfile = file("stats.txt", "r")
            stats = pickle.load(myfile)
            myfile.close()
            for game in stats:
                size = game[3] / 2
                #playerStats = game[4]
                # just worry about the buyers
                for x in range(4, 4 + size):
                    player = game[x]
                    if player[1] > 2:
                        wealthg2.append(player)
                    elif player[1] > 1:
                        wealthg1.append(player)
                    elif player[1] == 1:
                        wealth1.append(player)
                    elif player[1] > 0.5:
                        wealthl1.append(player)
                    else:
                        wealthl05.append(player)
            bucketwl05 = bucketEdgesBought(wealthl05)
            for elem in bucketwl05:
                print elem
        elif switch == 1:
            wealthg2 = []
            wealthg1 = []
            wealth1 = []
            wealthl1 = []
            wealthl05 = []
            # go through all the player instances in 
            myfile = file("stats.txt", "r")
            stats = pickle.load(myfile)
            myfile.close()
            for game in stats:
                size = game[3] / 2
                #playerStats = game[4]
                # just worry about the buyers
                for x in range(4, 4 + size):
                    player = game[x]
                    if player[1] > 2:
                        wealthg2.append(player)
                    elif player[1] > 1:
                        wealthg1.append(player)
                    elif player[1] == 1:
                        wealth1.append(player)
                    elif player[1] > 0.5:
                        wealthl1.append(player)
                    else:
                        wealthl05.append(player)
            bucketwg2 = bucketWealthInc(wealthg2)
            bucketwg1 = bucketWealthInc(wealthg1)
            bucketw1 = bucketWealthInc(wealth1)
            bucketwl1 = bucketWealthInc(wealthl1)
            bucketwl05 = bucketWealthInc(wealthl05)
            app = hippo.HDApp()
            canvas = app.canvas()
            hist = hippo.Display ("Histogram", [bucketwg2, ], ['Change in Wealth',] )
            canvas.addDisplay(hist)
            hist.setTitle("Change in wealth (init wealth > 2)")
            hist2 = hippo.Display ("Histogram", [bucketwg1, ], ['Change in Wealth',] )
            canvas.addDisplay(hist2)
            hist2.setTitle("Change in wealth (init wealth > 1, <= 2)")
            hist3 = hippo.Display ("Histogram", [bucketw1, ], ['Change in Wealth',] )
            canvas.addDisplay(hist3)
            hist3.setTitle("Change in wealth (init wealth = 1)")
            hist4 = hippo.Display ("Histogram", [bucketwl1, ], ['Change in Wealth',] )
            canvas.addDisplay(hist4)
            hist4.setTitle("Change in wealth (init wealth < 1, >= 0.5)")
            hist5 = hippo.Display ("Histogram", [bucketwl05, ], ['Change in Wealth',] )
            canvas.addDisplay(hist5)
            hist5.setTitle("Change in wealth (init wealth < 0.5)")
            print "done"
        elif switch == 2:
            wealthg2 = []
            wealthg1 = []
            wealth1 = []
            # go through all the player instances in 
            myfile = file("stats.txt", "r")
            stats = pickle.load(myfile)
            myfile.close()
            for game in stats:
                size = game[3] / 2
                #playerStats = game[4]
                # just worry about the buyers
                for x in range(4, 4 + size):
                    player = game[x]
                    if player[5] == 2:
                        wealthg2.append(player)
                    elif player[5] == 1:
                        wealthg1.append(player)
                    elif player[5] == 0:
                        wealth1.append(player)
            bucketwg2 = bucketWealthInc(wealthg2)
            bucketwg1 = bucketWealthInc(wealthg1)
            bucketw1 = bucketWealthInc(wealth1)
            app = hippo.HDApp()
            canvas = app.canvas()
            hist = hippo.Display ("Histogram", [bucketwg2, ], ['Change in Wealth',] )
            canvas.addDisplay(hist)
            hist.setTitle("Change in wealth (purchased 2 edges)")
            hist2 = hippo.Display ("Histogram", [bucketwg1, ], ['Change in Wealth',] )
            canvas.addDisplay(hist2)
            hist2.setTitle("Change in wealth (purchased 1 edge)")
            hist3 = hippo.Display ("Histogram", [bucketw1, ], ['Change in Wealth',] )
            canvas.addDisplay(hist3)
            hist3.setTitle("Change in wealth (purchased 0 edges)")
            print "done"
        elif switch == 3:
            wealthg2 = []
            wealthg1 = []
            wealth1 = []
            wealthl1 = []
            # go through all the player instances in 
            myfile = file("stats.txt", "r")
            stats = pickle.load(myfile)
            myfile.close()
            for game in stats:
                size = game[3] / 2
                cost = game[2]
                #playerStats = game[4]
                # just worry about the buyers
                for x in range(4, 4 + size):
                    player = game[x]
                    if cost > 0.5:
                        wealthg2.append(player)
                    elif cost > 0.3:
                        wealthg1.append(player)
                    elif cost > 0.1:
                        wealth1.append(player)
                    else:
                        wealthl1.append(player)
            bucket = bucketEdgesBought(wealthl1)
            for elem in bucket:
                print elem
        # bucket by wealth and cost
        # 0--5, 5-10
        # less than 1, 1, greater than 1
        elif switch == 4:
            w1 = []
            w2 = []
            w3 = []
            w4 = []
            w5 = []
            w6 = []
            # go through all the player instances in 
            myfile = file("stats.txt", "r")
            stats = pickle.load(myfile)
            myfile.close()
            for game in stats:
                size = game[3] / 2
                cost = game[2]
                #playerStats = game[4]
                # just worry about the buyers
                for x in range(4, 4 + size):
                    player = game[x]
                    if cost > 0.5:
                        if player[1] > 1:
                            w1.append(player)
                        elif player[1] == 1:
                            w2.append(player)
                        elif player[1] < 1:
                            w3.append(player)
                    else:
                        if player[1] > 1:
                            w4.append(player)
                        elif player[1] == 1:
                            w5.append(player)
                        elif player[1] < 1:
                            w6.append(player)
            bucketw1 = bucketWealthInc(w1)
            bucketw2 = bucketWealthInc(w2)
            bucketw3 = bucketWealthInc(w3)
            bucketw4 = bucketWealthInc(w4)
            bucketw5 = bucketWealthInc(w5)
            bucketw6 = bucketWealthInc(w6)
            app = hippo.HDApp()
            canvas = app.canvas()
            hist = hippo.Display ("Histogram", [bucketw1, ], ['Change in Wealth',] )
            canvas.addDisplay(hist)
            hist.setTitle("Change in wealth (init wealth > 1, cost > 0.5)")
            hist2 = hippo.Display ("Histogram", [bucketw2, ], ['Change in Wealth',] )
            canvas.addDisplay(hist2)
            hist2.setTitle("Change in wealth (init wealth = 1, cost > 0.5)")
            hist3 = hippo.Display ("Histogram", [bucketw3, ], ['Change in Wealth',] )
            canvas.addDisplay(hist3)
            hist3.setTitle("Change in wealth (init wealth < 1, cost > 0.5)")
            hist4 = hippo.Display ("Histogram", [bucketw4, ], ['Change in Wealth',] )
            canvas.addDisplay(hist4)
            hist4.setTitle("Change in wealth (init wealth > 1, cost < 0.5)")
            hist5 = hippo.Display ("Histogram", [bucketw5, ], ['Change in Wealth',] )
            canvas.addDisplay(hist5)
            hist5.setTitle("Change in wealth (init wealth = 1, cost < 0.5)")
            hist6 = hippo.Display ("Histogram", [bucketw6, ], ['Change in Wealth',] )
            canvas.addDisplay(hist6)
            hist6.setTitle("Change in wealth (init wealth < 1, cost < 0.5)")
            print "done"
        elif switch == 5:
            # in this analysis we would like 3 histograms
            # change in socialFn
            # change in socialFn when socialFn is low
            # change in socialFn when socialFn is high
            begSoc = []
            endSoc = []
            oldSoc = []
            # go through all the player instances in 
            myfile = file("stats.txt", "r")
            stats = pickle.load(myfile)
            myfile.close()
            for game in stats:
                begWealths = []
                endWealths = []
                size = game[3]
                for x in range(4, 4 + size):
                    player = game[x]
                    begWealths.append(player[1])
                    endWealths.append(player[2])
                begWealths = numpy.array(begWealths)
                endWealths = numpy.array(endWealths)
                oldSoc.append((socialFn(numpy.std(begWealths)), socialFn(numpy.std(endWealths))))
            oldSoc.sort()
            for elem in oldSoc:
                begSoc.append(elem[0])
                endSoc.append(elem[1])
            changeSoc = []
            for x in range(len(begSoc)):
                changeSoc.append(endSoc[x] - begSoc[x])
            soc1 = []
            soc2 = []
            for x in range(len(changeSoc)):
                if x < len(changeSoc) / 2:
                    soc1.append(changeSoc[x])
                else:
                    soc2.append(changeSoc[x])
            app = hippo.HDApp()
            canvas = app.canvas()
            hist = hippo.Display ("Histogram", [begSoc, ], ['Social Wealth',] )
            canvas.addDisplay(hist)
            hist.setTitle("Social Wealth at Beginning of Games")
            hist2 = hippo.Display ("Histogram", [endSoc, ], ['Social Wealth',] )
            canvas.addDisplay(hist2)
            hist2.setTitle("Social Wealth at End of Games")
            hist3 = hippo.Display ("Histogram", [changeSoc, ], ['Change in Wealth',] )
            canvas.addDisplay(hist3)
            hist3.setTitle("Change in Social Wealth During Games")
            hist4 = hippo.Display ("Histogram", [soc1, ], ['Change in Wealth',] )
            canvas.addDisplay(hist4)
            hist4.setTitle("Change in Social Wealth During Uneven Games")
            hist5 = hippo.Display ("Histogram", [soc2, ], ['Change in Wealth',] )
            canvas.addDisplay(hist5)
            hist5.setTitle("Change in Social Wealth During Even Games")
            print "done"

if __name__ == '__main__':

# calibrate params
# calibrate final eval fn
# calibrate edge costs
    e = Evaluator()
    #e.compare()
    #e.evaluateEdgeCosts()
    #e.parseCompareStats()
    e.collectLearnerStats()
    # took 702.7 secs
    #e.parseStats()
    #e.graphStats()