예제 #1
0
    def mainPane(self):
        locations = ["Tavern", "Shop", "Forest", "Inn", "Castle"]
        character_approval = False
        while character_approval != True:
            hero = Hero(Weapon().generate_weapon())
            print("Your character is " + hero.char.name +
                  "\nEquipped with a " + hero.get_weapon().name +
                  " that does " + str(hero.get_weapon().low_damage) + "-" +
                  str(hero.get_weapon().high_damage) + " damage.")
            char_generation = input("Do you approve of this character: ")
            if "Y" in char_generation.upper():
                character_approval = True

        while True:
            print("\nLocations: ")
            counter = 1
            for i in locations:
                print(str(counter) + ". " + i)
                counter += 1
            location_choice = input("Where would you like to go: ")
            if int(location_choice) is 1:
                Tavern(hero)
            if int(location_choice) is 2:
                Shop(hero)
            if int(location_choice) is 3:
                forest = Forest()
                forest.entry(hero)
            if int(location_choice) is 4:
                hotel = Inn(hero)
            if int(location_choice) is 5:
                Castle(hero)
            input()
예제 #2
0
  def test_getNeighborEdgeCase(self):
    location = (0, 0)
    forest = Forest(self.size)

    neighbor_locations = forest.getNeighborLocations(location)

    self.assertEqual(len(neighbor_locations), 2)
예제 #3
0
 def getFather(self, tree):
     if (self.isEmpty()):
         return
     else:
         
         f = Forest([self])
         
         return f.getFatherOfTree(tree)
예제 #4
0
 def getDegree(self):
     if self.isEmpty():
         return 0
     else:
         # transform the rooted tree in forest
         f = Forest([self])
         # call the coresponding method on the forest
         return f.getDegree()
예제 #5
0
 def getAscending(self, root, tree):
     if self.isEmpty():
         return []
     else:
         # transform the rooted tree in forest
         f = Forest([self])
         # call the coresponding method on the forest
         return f.getAscending(root, tree)
예제 #6
0
  def test_isInBounds(self):
    forest = Forest(self.size)

    location_inbounds = (1, 3)
    self.assertTrue(forest.isInBounds(location_inbounds))

    location_outofbounds = (self.size, self.size + 1)
    self.assertFalse(forest.isInBounds(location_outofbounds))
예제 #7
0
 def displayWidth(self):
     # do nothing if the rooted tree is empty
     if self.isEmpty():
         return
     else:
         # transform the rooted tree in forest
         f = Forest([self])
         # call the coresponding method on the forest
         return f.displayWidth()
 def newForest(self):
     forest = Forest()
     for i in xrange(0, self.numTrees):
         position = Point(trand(self.xrange), trand(self.yrange))
         tree = Tree(position=position, value = trand(self.valuerange), 
                     length = trand(self.lengthrange))
         tree.id = i
         forest.addTree(tree)
     return forest
예제 #9
0
  def test_elementManipulation(self):
    location = (1, 3)
    value = 5

    forest = Forest(self.size)
    forest.setValue(location, value)
    get_value = forest.getValue(location)

    self.assertEqual(get_value, value)
예제 #10
0
 def __init__(self, player):
     self.array = []
     self.player = player
     self.c = 0
     self.towns = [Town("Farnfos", [0, 0]), Town("Lunari", [1, 1]),
                   Town("Cewmann", [2, 2]),
                   Town("Caister", [3, 3]), Town("Aramore", [4, 4]),
                   Town("Kilerth", [5, 5]),
                   Town("Eldhams", [6, 6]), Town("Cirrane", [7, 7]),
                   Town("Warcest", [8, 8])]
     self.forest = Forest()
예제 #11
0
 def __init__(self, facilities, customers, params):
     self.facilities = dict(
         zip([facility.index for facility in facilities],
             [facility for facility in facilities]))
     self.customers = customers
     self.subproblemSolutionForest = Forest()
     self.currentIteration = 0
     self.mip = MIP(facilities, customers,
                    "Instance_%s_%s" % (len(facilities), len(customers)),
                    params["mipSolver"])
     self.facilitiesCount = len(facilities)
     self.quantiles = []
     self.params = params
     self.totalDemand = sum([customer.demand for customer in customers])
     self.currentObjectiveFunction = 0
     self.currentSolutionAssignment = []
    def init_UI(self):

        self.FAQ.clicked.connect(self.show_faq)

        self.Generate_button.clicked.connect(self.generate_image_main_logic)

        self.Save_button.setEnabled(False)
        self.Save_button.clicked.connect(self.save_image)

        # base_settings_update connections
        self.base_settings = {'size': 200, 'zoom': 50}
        self.Size_ComboBox.valueChanged.connect(self.base_settings_update)
        self.Zoom_ComboBox.valueChanged.connect(self.base_settings_update)
        # Biomes
        self.Forest = Forest(self.ForestLayout)
        self.Desert = Desert(self.DesertLayout)
        self.Frost = Frost(self.FrostLayout)
예제 #13
0
def forestTest(trainSet,
               trainLab,
               testSet,
               testLab,
               ntree,
               nbayes,
               pruneTreeSplit=0.0):
    forest = Forest(ntree, nbayes, pruneSplit=pruneTreeSplit)
    forest.fit(trainSet, trainLab)
    predLab = forest.predict(testSet)
    print("forest (trees: {}, bayes:{}) errors:".format(ntree, nbayes))
    print(sum(testLab != predLab))
    print(1 - sum(testLab != predLab) / len(testLab))
    print("forest (trees: {}, bayes:{}) confusion matrix:".format(
        ntree, nbayes))
    print(confusion_matrix(testLab, predLab))
    print()
예제 #14
0
파일: main.py 프로젝트: iccowan/CSC_117
def main():
    # Init the forest
    forest = Forest()
    win = forest.getWindow()

    # Draw an input box
    e = Entry(Point(150, 75), 10)
    e.setFill("white")
    e.draw(win)

    # Draw the text above the box
    text1 = Text(Point(150, 86), "Probability of Spreading")
    text = Text(Point(150, 81), "Enter 0-1 (Ex. 0.25)")
    text1.draw(win)
    text.draw(win)

    # Draw two buttons
    createButton(0, win)
    createButton(1, win)

    # Finally, run the simulation!
    closeProgram = False

    while not closeProgram:
        # Get the selected tree and burn probability
        tree, burnPercent = getTreeAndPercent(win, forest, e)

        # Begin the fire!
        forest.beginBurn(tree, burnPercent)

        forest.displayPercentBurned()

        # Get a click and see if they want to close the program
        # or if they want to reset and go again
        clickpt = win.getMouse()

        while not(clickpt.getX() <= 170 and clickpt.getX() >= 130 and \
                  ((clickpt.getY() <= 55 and clickpt.getY() >= 45) or \
                  (clickpt.getY() <= 35 and clickpt.getY() >= 25))):
            # Get another click
            clickpt = win.getMouse()

        if clickpt.getX() <= 170 and clickpt.getX() >= 130 and \
           clickpt.getY() <= 55 and clickpt.getY() >= 45:
            # Reset the forest
            forest.resetForest()
        elif clickpt.getX() <= 170 and clickpt.getX() >= 130 and \
             clickpt.getY() <= 35 and clickpt.getY() >= 25:
            # Close the window
            closeProgram = True
예제 #15
0
  def test_addTree(self):
    forest = Forest(self.size)
    location1 = (1, 3)
    location2 = (2, 3)
    location3 = (4, 4)

    forest.addTree(location1)
    forest.addTree(location2)
    forest.addTree(location3)

    self.assertEqual(forest.getValue(location1), 2)
    self.assertEqual(forest.getValue(location2), 2)
    self.assertEqual(forest.getValue(location3), 1)
예제 #16
0
  def test_getForestLocations(self):
    forest = Forest(self.size)
    location1 = (1, 2)
    location2 = (1, 3)
    location3 = (2, 3)

    forest.addTree(location1)
    forest.addTree(location2)
    forest.addTree(location3)

    tree_locations = forest.getForestLocations(location1)

    self.assertEqual(len(tree_locations), 3)
예제 #17
0
  def test_getForests(self):
    forest = Forest(self.size)
    location1 = (1, 3)
    location2 = (2, 3)
    location3 = (4, 4)
    location4 = (1, 1)
    location5 = (1, 2)
    location6 = (4, 2)

    forest.addTree(location1)
    forest.addTree(location2)
    forest.addTree(location3)
    forest.addTree(location4)
    forest.addTree(location5)
    forest.addTree(location6)

    forests = forest.getForests()
    num_forests = 3

    self.assertEqual(len(forests), num_forests)
예제 #18
0
  def test_getUnoccupiedLocations(self):
    forest = Forest(self.size)
    location1 = (1, 3)
    location2 = (2, 3)
    location3 = (4, 4)

    forest.addTree(location1)
    forest.addTree(location2)
    forest.addTree(location3)

    unoccupied_locations = forest.getUnoccupiedLocations()
    expected_ammount = self.size * self.size - 3

    self.assertEqual(len(unoccupied_locations), expected_ammount)
예제 #19
0
    def nextState(self, action):
        response = self.scenario.nextState(action)
        if self.game_state == "mountain":
            if "Forest" == response:
                self.game_state = "Forest"
                self.scenario = Forest()
            else:
                self.game_state = "Castle"
                #self.scenario = Castle()

        elif self.game_state == "Forest":
            if "Town" == response:
                self.game_state = "Town"
                self.scenario = Town()

        elif self.game_state == "Castle":
            pass
        else:
            #game_state is "town"
            pass
예제 #20
0
    def __evaluate(self, newObj, assignments, candidateForest, cluster):
        if (self.DEBUG_MESSAGES):
            print("=============================")
            print("Evaluate Method Started...")
            print(
                "Current Partial Objective: %s || Candidate Partial Objective %s"
                % (newObj, candidateForest.getTotalCost()))

        if (newObj - candidateForest.getTotalCost() <= self.EPS):

            newSolution = Forest()
            newSolution.buildForestFromArray(
                self.subproblemSolutionForest.getAssignmentsArray(),
                self.facilities, self.customers)
            partialSolution = Forest()
            partialSolution.buildForestFromDict(
                Util.getDictSolutionFromMIP(assignments), self.facilities,
                self.customers)
            currentForestObj = self.subproblemSolutionForest.getTotalCost()

            newFacilities = set()
            previousFacilities = set()

            for tree in candidateForest.getTrees().values():
                newSolution.removeTree(tree.getRoot().index)
                previousFacilities.add(tree.getRoot().index)

            for tree in partialSolution.getTrees().values():
                newSolution.addTree(Tree(tree.getRoot()))
                newFacilities.add(tree.getRoot().index)
                for node in tree.getNodes().values():
                    newSolution.getTrees().get(
                        tree.getRoot().index).addNode(node)

            #Facilities that were in the solution, but was not even selected as candidates
            clusterIntersection = set([
                tree.getRoot().index
                for tree in self.subproblemSolutionForest.getTrees().values()
            ]).intersection(cluster)
            notInterestingFacilities = clusterIntersection.difference(
                previousFacilities)

            for facilityIndex in notInterestingFacilities:
                newSolution.removeTree(facilityIndex)

            newSolution.updateStatistics()

            previousCandidates = list(
                previousFacilities.difference(
                    newFacilities.intersection(previousFacilities)))

            if (len(previousCandidates) == 0):
                previousCandidates = list(newFacilities)

            previousCandidates.extend(list(notInterestingFacilities))

            print("Current Objective: %s || Candidate Objective: %s" %
                  (currentForestObj, newSolution.getTotalCost()))

            if (self.params["improvementType"] == ImprovementType.Best):
                if (Util.truncate(
                        Util.truncate(newSolution.getTotalCost(), 10) -
                        Util.truncate(
                            self.subproblemSolutionForest.getTotalCost(), 10),
                        10) <= self.EPS):
                    if (self.DEBUG_MESSAGES):
                        print("NEW SOLUTION FOUND!")
                    self.subproblemSolutionForest.buildForestFromArray(
                        newSolution.getAssignmentsArray(), self.facilities,
                        self.customers)

                    newForestObj = self.subproblemSolutionForest.getTotalCost()

                    self.__updateFrequency(list(newFacilities),
                                           self.ASSIGNMENT_REWARD)

                    previousCandidates = list(
                        previousFacilities.difference(
                            newFacilities.intersection(previousFacilities)))

                    if (len(previousCandidates) == 0):
                        previousCandidates = list(newFacilities)

                    previousCandidates.extend(list(notInterestingFacilities))

                    reward = Util.truncate(
                        float(len(newFacilities)) /
                        float(len(previousCandidates)), 3)

                    self.__updateFrequency(previousCandidates, reward)

                    if (self.DEBUG_MESSAGES):
                        print("Previous Objective: %s || New Objective: %s" %
                              (currentForestObj, newForestObj))
                        print("Partial Solution")
                        partial = ""
                        partial = '%.2f' % self.subproblemSolutionForest.getTotalCost(
                        ) + ' ' + str(0) + '\n'
                        partial += ' '.join(
                            map(
                                str,
                                self.subproblemSolutionForest.
                                getAssignmentsArray()))
                        print(partial)
                else:
                    candidates = [
                        tree.getRoot().index
                        for tree in candidateForest.getTrees().values()
                    ]
                    #reward = (Util.truncate(float(candidateForest.getTreesCount()/self.facilitiesCount),3))*self.ASSIGNMENT_REWARD
                    reward = self.NO_ASSIGNMENT_REWARD
                    self.__updateFrequency(candidates, reward)

            elif self.params["improvementType"] == ImprovementType.First:
                self.subproblemSolutionForest.buildForestFromArray(
                    newSolution.getAssignmentsArray(), self.facilities,
                    self.customers)

                newForestObj = self.subproblemSolutionForest.getTotalCost()

                self.__updateFrequency(list(newFacilities),
                                       self.ASSIGNMENT_REWARD)

                previousCandidates = list(
                    previousFacilities.difference(
                        newFacilities.intersection(previousFacilities)))

                if (len(previousCandidates) == 0):
                    previousCandidates = list(newFacilities)

                previousCandidates.extend(list(notInterestingFacilities))

                reward = Util.truncate(
                    float(len(newFacilities)) / float(len(previousCandidates)),
                    3)

                self.__updateFrequency(previousCandidates, reward)

                if (self.DEBUG_MESSAGES):
                    print("Previous Objective: %s || New Objective: %s" %
                          (currentForestObj, newForestObj))
                    print("Partial Solution")
                    partial = ""
                    partial = '%.2f' % self.subproblemSolutionForest.getTotalCost(
                    ) + ' ' + str(0) + '\n'
                    partial += ' '.join(
                        map(
                            str,
                            self.subproblemSolutionForest.getAssignmentsArray(
                            )))
                    print(partial)

                candidates = [
                    tree.getRoot().index
                    for tree in candidateForest.getTrees().values()
                ]
                #reward = (Util.truncate(float(candidateForest.getTreesCount()/self.facilitiesCount),3))*self.ASSIGNMENT_REWARD
                reward = self.NO_ASSIGNMENT_REWARD
                self.__updateFrequency(candidates, reward)

        if (self.DEBUG_MESSAGES):
            print("Evaluate Method Finished...")
            print("=============================")
예제 #21
0
class LNS:

    EPS = 1.e-10
    DEBUG_MESSAGES = False
    ASSIGNMENT_REWARD = 1
    INITIAL_REWARD = 0.5
    NO_ASSIGNMENT_REWARD = 0.25
    MAX_PROBLEM_SIZE = 25000

    def __init__(self, facilities, customers, params):
        self.facilities = dict(
            zip([facility.index for facility in facilities],
                [facility for facility in facilities]))
        self.customers = customers
        self.subproblemSolutionForest = Forest()
        self.currentIteration = 0
        self.mip = MIP(facilities, customers,
                       "Instance_%s_%s" % (len(facilities), len(customers)),
                       params["mipSolver"])
        self.facilitiesCount = len(facilities)
        self.quantiles = []
        self.params = params
        self.totalDemand = sum([customer.demand for customer in customers])
        self.currentObjectiveFunction = 0
        self.currentSolutionAssignment = []

    def __InitializeProblem(self, facilities, customers):
        self.currentIteration = 0
        self.clusterAreas = Preprocessing.getClusters(
            facilities.values(), self.params["quantile_intervals"])
        if (self.params["initialSolutionFunction"] ==
                InitialSolutionFunction.Radius):
            Preprocessing.getDistanceQuantiles(
                facilities, self.params["quantile_intervals"])
            self.subproblemSolutionForest.buildForestFromArray(
                Util.formatSolutionFromMIP(
                    Preprocessing.getRadiusDistanceInitialSolution(
                        facilities, customers, self.clusterAreas.get(0))),
                self.facilities, self.customers)
        else:
            self.subproblemSolutionForest.buildForestFromArray(
                Util.formatSolutionFromMIP(
                    Preprocessing.getNearestNeighbourInitialSolution(
                        facilities, customers,
                        self.params["initialSolutionFunction"])),
                self.facilities, self.customers)

        for facility in facilities.keys():
            self.facilities[facility] = self.facilities[facility]._replace(
                frequency=self.INITIAL_REWARD)

    def __getQuantiles(self):
        firstQuantile = Util.truncate(1.0 / float(len(self.clusterAreas)), 10)

        quantileIntervals = len(self.clusterAreas)

        quantile = firstQuantile

        for interval in range(0, quantileIntervals - 1):
            self.quantiles.append(quantile)
            quantile = Util.truncate(quantile + firstQuantile, 10)

        self.quantiles.append(Util.truncate(quantile - firstQuantile, 10))

    def __getCandidateFacilities(self,
                                 cluster,
                                 demand,
                                 threshold,
                                 fulfillDemand=True):

        freqs = [self.facilities[i].frequency for i in cluster]
        candidateIndexes = Util.filterbyThreshold(freqs, threshold,
                                                  self.currentIteration + 1)
        result = [cluster[i] for i in candidateIndexes]

        candidatesCapacity = 0
        for index in result:
            candidatesCapacity = candidatesCapacity + self.facilities[
                index].capacity

        print("Demand: %s || Capacity: %s" % (demand, candidatesCapacity))

        if (candidatesCapacity < demand):
            if fulfillDemand:
                remainingFacilitiesIndex = set(cluster).difference(
                    set(cluster).intersection(set(result)))
                remainingFacilities = [
                    self.facilities[i] for i in remainingFacilitiesIndex
                ]
                remainingFacilities.sort(key=lambda x: x.cost_per_capacity,
                                         reverse=True)
                print("Demand above Capacity")
                for facility in remainingFacilities:
                    result.append(facility.index)
                    candidatesCapacity = candidatesCapacity + facility.capacity
                    if (candidatesCapacity >= demand):
                        print("Demand: %s || New Capacity: %s" %
                              (demand, candidatesCapacity))
                        break
            else:
                return None

        return result

    def __updateFrequency(self, facilities, reward):

        for index in facilities:
            if (index not in self.facilities.keys()):
                input("key does not exists!")
            freq = self.facilities[index].frequency + reward
            self.facilities[index] = self.facilities[index]._replace(
                frequency=freq)

    def __destroy(self, cluster):

        if (self.DEBUG_MESSAGES):
            print("=============================")
            print("Destroy Method Started...")

        clusterDemand = 0
        for facilityIndex in cluster:
            if (facilityIndex
                    in self.subproblemSolutionForest.getTrees().keys()):
                for node in self.subproblemSolutionForest.getTrees().get(
                        facilityIndex).getNodes().values():
                    clusterDemand = clusterDemand + node.demand

        #candidateFacilities = self.__getCandidateFacilities(cluster,clusterDemand,Util.truncate(self.quantiles[self.currentIteration],5))
        candidateFacilities = copy.deepcopy(cluster)
        print("Current Forest: %s/%s - Candidate Facilities: %s/%s" %
              (self.subproblemSolutionForest.getTreesCount(),
               self.subproblemSolutionForest.getTotalNodes(),
               len(candidateFacilities), len(cluster)))

        reassignmentCandidates = Forest()

        for facilityIndex in candidateFacilities:
            if (facilityIndex not in reassignmentCandidates.getTrees().keys()):
                reassignmentCandidates.addTree(
                    Tree(self.facilities[facilityIndex]))

        for facilityIndex in cluster:
            if (facilityIndex
                    in self.subproblemSolutionForest.getTrees().keys()):
                for node in self.subproblemSolutionForest.getTrees().get(
                        facilityIndex).getNodes().values():
                    reassignmentCandidates.getTrees().get(
                        candidateFacilities[0]).addNode(node)

        reassignmentCandidates.updateStatistics()

        if (self.DEBUG_MESSAGES):
            print("Facilities: %s - Customers %s" %
                  (reassignmentCandidates.getTreesCount(),
                   reassignmentCandidates.getTotalNodes()))
            print("Destroy Method Finished...")
            print("=============================")

        return reassignmentCandidates

    def __repair(self, candidatesFacility, candidatesCustomer):
        if (self.DEBUG_MESSAGES):
            print("=============================")
            print("Repair Method Started...")
        self.mip.clear()
        self.mip.initialize(
            candidatesFacility, candidatesCustomer, "Instance_%s_%s" %
            (len(candidatesFacility), len(candidatesCustomer)),
            self.params["mipSolver"])
        obj, assignments, status = self.mip.optimize(
            self.params["mipTimeLimit"])

        if (self.DEBUG_MESSAGES):
            print("Repair Method Finished...")
            print("=============================")

        return obj, assignments, status

    def __evaluate(self, newObj, assignments, candidateForest, cluster):
        if (self.DEBUG_MESSAGES):
            print("=============================")
            print("Evaluate Method Started...")
            print(
                "Current Partial Objective: %s || Candidate Partial Objective %s"
                % (newObj, candidateForest.getTotalCost()))

        if (newObj - candidateForest.getTotalCost() <= self.EPS):

            newSolution = Forest()
            newSolution.buildForestFromArray(
                self.subproblemSolutionForest.getAssignmentsArray(),
                self.facilities, self.customers)
            partialSolution = Forest()
            partialSolution.buildForestFromDict(
                Util.getDictSolutionFromMIP(assignments), self.facilities,
                self.customers)
            currentForestObj = self.subproblemSolutionForest.getTotalCost()

            newFacilities = set()
            previousFacilities = set()

            for tree in candidateForest.getTrees().values():
                newSolution.removeTree(tree.getRoot().index)
                previousFacilities.add(tree.getRoot().index)

            for tree in partialSolution.getTrees().values():
                newSolution.addTree(Tree(tree.getRoot()))
                newFacilities.add(tree.getRoot().index)
                for node in tree.getNodes().values():
                    newSolution.getTrees().get(
                        tree.getRoot().index).addNode(node)

            #Facilities that were in the solution, but was not even selected as candidates
            clusterIntersection = set([
                tree.getRoot().index
                for tree in self.subproblemSolutionForest.getTrees().values()
            ]).intersection(cluster)
            notInterestingFacilities = clusterIntersection.difference(
                previousFacilities)

            for facilityIndex in notInterestingFacilities:
                newSolution.removeTree(facilityIndex)

            newSolution.updateStatistics()

            previousCandidates = list(
                previousFacilities.difference(
                    newFacilities.intersection(previousFacilities)))

            if (len(previousCandidates) == 0):
                previousCandidates = list(newFacilities)

            previousCandidates.extend(list(notInterestingFacilities))

            print("Current Objective: %s || Candidate Objective: %s" %
                  (currentForestObj, newSolution.getTotalCost()))

            if (self.params["improvementType"] == ImprovementType.Best):
                if (Util.truncate(
                        Util.truncate(newSolution.getTotalCost(), 10) -
                        Util.truncate(
                            self.subproblemSolutionForest.getTotalCost(), 10),
                        10) <= self.EPS):
                    if (self.DEBUG_MESSAGES):
                        print("NEW SOLUTION FOUND!")
                    self.subproblemSolutionForest.buildForestFromArray(
                        newSolution.getAssignmentsArray(), self.facilities,
                        self.customers)

                    newForestObj = self.subproblemSolutionForest.getTotalCost()

                    self.__updateFrequency(list(newFacilities),
                                           self.ASSIGNMENT_REWARD)

                    previousCandidates = list(
                        previousFacilities.difference(
                            newFacilities.intersection(previousFacilities)))

                    if (len(previousCandidates) == 0):
                        previousCandidates = list(newFacilities)

                    previousCandidates.extend(list(notInterestingFacilities))

                    reward = Util.truncate(
                        float(len(newFacilities)) /
                        float(len(previousCandidates)), 3)

                    self.__updateFrequency(previousCandidates, reward)

                    if (self.DEBUG_MESSAGES):
                        print("Previous Objective: %s || New Objective: %s" %
                              (currentForestObj, newForestObj))
                        print("Partial Solution")
                        partial = ""
                        partial = '%.2f' % self.subproblemSolutionForest.getTotalCost(
                        ) + ' ' + str(0) + '\n'
                        partial += ' '.join(
                            map(
                                str,
                                self.subproblemSolutionForest.
                                getAssignmentsArray()))
                        print(partial)
                else:
                    candidates = [
                        tree.getRoot().index
                        for tree in candidateForest.getTrees().values()
                    ]
                    #reward = (Util.truncate(float(candidateForest.getTreesCount()/self.facilitiesCount),3))*self.ASSIGNMENT_REWARD
                    reward = self.NO_ASSIGNMENT_REWARD
                    self.__updateFrequency(candidates, reward)

            elif self.params["improvementType"] == ImprovementType.First:
                self.subproblemSolutionForest.buildForestFromArray(
                    newSolution.getAssignmentsArray(), self.facilities,
                    self.customers)

                newForestObj = self.subproblemSolutionForest.getTotalCost()

                self.__updateFrequency(list(newFacilities),
                                       self.ASSIGNMENT_REWARD)

                previousCandidates = list(
                    previousFacilities.difference(
                        newFacilities.intersection(previousFacilities)))

                if (len(previousCandidates) == 0):
                    previousCandidates = list(newFacilities)

                previousCandidates.extend(list(notInterestingFacilities))

                reward = Util.truncate(
                    float(len(newFacilities)) / float(len(previousCandidates)),
                    3)

                self.__updateFrequency(previousCandidates, reward)

                if (self.DEBUG_MESSAGES):
                    print("Previous Objective: %s || New Objective: %s" %
                          (currentForestObj, newForestObj))
                    print("Partial Solution")
                    partial = ""
                    partial = '%.2f' % self.subproblemSolutionForest.getTotalCost(
                    ) + ' ' + str(0) + '\n'
                    partial += ' '.join(
                        map(
                            str,
                            self.subproblemSolutionForest.getAssignmentsArray(
                            )))
                    print(partial)

                candidates = [
                    tree.getRoot().index
                    for tree in candidateForest.getTrees().values()
                ]
                #reward = (Util.truncate(float(candidateForest.getTreesCount()/self.facilitiesCount),3))*self.ASSIGNMENT_REWARD
                reward = self.NO_ASSIGNMENT_REWARD
                self.__updateFrequency(candidates, reward)

        if (self.DEBUG_MESSAGES):
            print("Evaluate Method Finished...")
            print("=============================")

    def optimize(self):
        start = time.time()
        clock = Clock()
        clock.setStart(start)
        if (self.DEBUG_MESSAGES):
            print("=============================")
            print("LNS Optimize Method Started...")

        customerSubset = copy.deepcopy(self.customers)
        facilitySubet = copy.deepcopy(self.facilities)
        self.__InitializeProblem(facilitySubet, customerSubset)
        self.__getQuantiles()
        self.currentObjectiveFunction = self.subproblemSolutionForest.getTotalCost(
        )
        self.currentSolutionAssignment = self.subproblemSolutionForest.getAssignmentsArray(
        )
        initialQuantiles = copy.deepcopy(self.quantiles)
        quantileSize = len(initialQuantiles)
        quantilesCount = 0
        customerCount = len(self.customers)
        noImprovementIterations = 0
        while True:
            if (clock.isTimeOver(time.time(),
                                 self.params["executionTimeLimit"])):
                break

            iterationsCount = len(self.clusterAreas)
            for iteration in range(0, iterationsCount):
                self.currentIteration = iteration
                clustersCount = 0
                clustersSize = len(self.clusterAreas.get(iteration))
                for cluster in self.clusterAreas.get(iteration).values():
                    clustersCount = clustersCount + 1
                    print("Iteration: %s/%s || Instance: %s_%s" %
                          (quantilesCount + 1, quantileSize,
                           self.facilitiesCount, customerCount))
                    print("Subproblem: %s/%s" %
                          (self.currentIteration + 1, iterationsCount))
                    candidateForest = self.__destroy(cluster)
                    if (candidateForest.getTreesCount() *
                            candidateForest.getTotalNodes() >
                            self.MAX_PROBLEM_SIZE):
                        print(
                            "Problem instance is larger than limit. Skipping..."
                        )
                        candidateFacilities = [
                            tree.getRoot()
                            for tree in candidateForest.getTrees().values()
                        ]
                        self.__updateFrequency(
                            dict([(facility.index, facility)
                                  for facility in candidateFacilities]),
                            self.NO_ASSIGNMENT_REWARD)
                        continue

                    cFacilities, cCustomers = candidateForest.getData()

                    print(
                        "Current Cluster: %s/%s || Facilities: %s || Customers Assigned: %s"
                        % (clustersCount, clustersSize,
                           candidateForest.getTreesCount(),
                           candidateForest.getTotalNodes()))
                    if (candidateForest.getTotalNodes() == 0):
                        if (self.DEBUG_MESSAGES):
                            print("No Customers Assigned... Continue")
                        continue

                    obj, assignment, status = self.__repair(
                        cFacilities, cCustomers)

                    if (status == 'optimal'):
                        self.__evaluate(obj, assignment, candidateForest,
                                        cluster)
                    else:
                        print("No Optimal Solution Found for this instance")
                        candidateFacilities = [
                            tree.getRoot()
                            for tree in candidateForest.getTrees().values()
                        ]
                        self.__updateFrequency(
                            dict([(facility.index, facility)
                                  for facility in candidateFacilities]),
                            self.ASSIGNMENT_REWARD)

                    print("Subproblem Forest: %s/%s" %
                          (self.subproblemSolutionForest.getTreesCount(),
                           self.subproblemSolutionForest.getTotalNodes()))
                    print("Subproblem Objective Funciton: %s" %
                          self.subproblemSolutionForest.getTotalCost())
                    print("Current Objective Function: %s" %
                          self.currentObjectiveFunction)

                if (self.DEBUG_MESSAGES):
                    print("Partial Solution")
                    partial = ""
                    partial = '%.2f' % self.subproblemSolutionForest.getTotalCost(
                    ) + ' ' + str(0) + '\n'
                    partial += ' '.join(
                        map(
                            str,
                            self.subproblemSolutionForest.getAssignmentsArray(
                            )))
                    print(partial)

            if (self.currentObjectiveFunction >=
                    self.subproblemSolutionForest.getTotalCost()):
                self.currentObjectiveFunction = self.subproblemSolutionForest.getTotalCost(
                )
                self.currentSolutionAssignment = self.subproblemSolutionForest.getAssignmentsArray(
                )
            else:
                noImprovementIterations = noImprovementIterations + 1

            print("====================================================")
            print("CURRENT OBJECTIVE FUNCTION: %s" %
                  self.currentObjectiveFunction)
            print("====================================================")
            if (quantilesCount >= quantileSize):
                print("Maximum Iteration Count Reached! Stopping...")
                break

            if (noImprovementIterations >
                    self.params["noImprovementIterationLimit"]):
                print("No improvement limit reached! Stopping the search...")
                break

            ##filtrar as facilities mais interessantes e jogar no facility subset
            candidates = [
                facility.index for facility in facilitySubet.values()
            ]
            lastCandidateCount = len(candidates)
            while quantilesCount < quantileSize and len(
                    candidates) == lastCandidateCount:
                candidates = self.__getCandidateFacilities(
                    candidates, self.totalDemand,
                    Util.truncate(initialQuantiles[quantilesCount], 5), False)
                quantilesCount = quantilesCount + 1

            if (candidates is None or len(candidates) == 0
                    or len(candidates) == lastCandidateCount):
                break

            facilitySubet = dict(
                zip([index for index in candidates],
                    [facilitySubet[index] for index in candidates]))
            self.facilities = facilitySubet
            self.__InitializeProblem(facilitySubet, customerSubset)
            self.__getQuantiles()

        return self.currentObjectiveFunction, self.currentSolutionAssignment
예제 #22
0
    def __destroy(self, cluster):

        if (self.DEBUG_MESSAGES):
            print("=============================")
            print("Destroy Method Started...")

        clusterDemand = 0
        for facilityIndex in cluster:
            if (facilityIndex
                    in self.subproblemSolutionForest.getTrees().keys()):
                for node in self.subproblemSolutionForest.getTrees().get(
                        facilityIndex).getNodes().values():
                    clusterDemand = clusterDemand + node.demand

        #candidateFacilities = self.__getCandidateFacilities(cluster,clusterDemand,Util.truncate(self.quantiles[self.currentIteration],5))
        candidateFacilities = copy.deepcopy(cluster)
        print("Current Forest: %s/%s - Candidate Facilities: %s/%s" %
              (self.subproblemSolutionForest.getTreesCount(),
               self.subproblemSolutionForest.getTotalNodes(),
               len(candidateFacilities), len(cluster)))

        reassignmentCandidates = Forest()

        for facilityIndex in candidateFacilities:
            if (facilityIndex not in reassignmentCandidates.getTrees().keys()):
                reassignmentCandidates.addTree(
                    Tree(self.facilities[facilityIndex]))

        for facilityIndex in cluster:
            if (facilityIndex
                    in self.subproblemSolutionForest.getTrees().keys()):
                for node in self.subproblemSolutionForest.getTrees().get(
                        facilityIndex).getNodes().values():
                    reassignmentCandidates.getTrees().get(
                        candidateFacilities[0]).addNode(node)

        reassignmentCandidates.updateStatistics()

        if (self.DEBUG_MESSAGES):
            print("Facilities: %s - Customers %s" %
                  (reassignmentCandidates.getTreesCount(),
                   reassignmentCandidates.getTotalNodes()))
            print("Destroy Method Finished...")
            print("=============================")

        return reassignmentCandidates
예제 #23
0
    # nos movemos hacia el frame que se desea evaluar.
    imagen_original.seek(frame)
    imagen_procesada.seek(frame)

    # imprimimos la imagen original y procesada
    # imagen_original.show()
    # imagen_procesada.show()

    imagen_original.save("original.png")

    # imprimimos las imagenes por los clasificadores
    imagen_caracteristicas = myImage(512, 512)
    imagen_caracteristicas.readDataFromCSV("Datos/" + str(frame) + ".csv")

    # creamos bosque para clasificar
    forest = Forest()

    # imprimimos imagen por las caracteristicas
    forest.generarImagenArbolIntensidad(
        imagen_caracteristicas).obtenerImagenPorClase().show()
    forest.generarImagenArbolGradiente(
        imagen_caracteristicas).obtenerImagenPorClase().show()
    forest.generarImagenArbolLaplaciano(
        imagen_caracteristicas).obtenerImagenPorClase().show()

    # imprimimos imagen utilizando el bosque
    forest.generarImagenUsandoBosque(
        imagen_caracteristicas).obtenerImagenPorClase().show()

if EvOtrosClasificadores:
예제 #24
0
	def __init__(self,components,nclasses=2,class_dist=np.array([]),p=0):
		


		'''
		Grow the Forest and store the leaves to compute a function to label the points
		'''

		self.components = map(np.array,components)
		self.p = p
		self.num_components = len(components)
		self.num_nodes = np.array(map(np.prod,components)) + 1 
		self.num_vars = map(len,components)
		self.n = sum(self.num_vars)

		self.forest = Forest(components)
		self.leaves = self.forest.get_leaves()
		self.nleaves = len(self.leaves)
		
		self.cardinalities = np.concatenate([self.components])[0]

		if len(class_dist) == 0:
			self.nclasses = nclasses
			self.classes = ['C%d'%(x) for x in np.arange(1,self.nclasses+1)]
			self.class_dist = class_dist

		else:
			self.class_dist=np.array(class_dist)
			self.nclasses = len(self.class_dist)
			self.classes = ['C%d'%(x) for x in np.arange(1,self.nclasses+1)]
			self.class_limit = np.floor(self.class_dist * self.nleaves)



		'''
		Assign leaves to classes
		
		Currently:
			(1) deterministically switching the classes of the leaves 
			(2) Any number of classes (provided the number is less than the number of leaves)
		'''

		self.label_function = {}
		if len(self.class_dist) == 0:
			counter = 1

			for leaf in self.leaves:
				self.label_function[leaf] = self.classes[np.mod(counter,self.nclasses)]
				counter = counter + 1
		
		else:
			self.class_counts = np.zeros(self.nclasses)
			counter = 0

			for leaf in self.leaves:
				if self.class_counts[ np.mod(counter,self.nclasses)  ] < self.class_limit[np.mod(counter,self.nclasses)]:
					self.label_function[leaf] = self.classes[np.mod(counter,self.nclasses)]
					self.class_counts[np.mod(counter,self.nclasses) ] += 1 
					counter = counter + 1
				else:
					possible_labels, = np.where(self.class_counts < self.class_limit) 
					possible_labels = possible_labels+1
					if(len(possible_labels)>0):
						alternative_label = np.random.choice(possible_labels)
						self.label_function[leaf] = 'C%d'%alternative_label
						self.class_counts[alternative_label-1] += 1 
					else:
						self.label_function[leaf]='C1'
						self.class_counts[0] += 1
					counter = counter + 1
예제 #25
0
hyper_parameters_options = [
    {
        'number_of_trees': 5,
        'number_of_attr_samples': 5
    }
]

print(f'Dataset será dividido em {divisions} partes, das quais uma para teste e uma para validação')

dataset = DatasetFile("path").read
divisor = StratifiedDivisor(dataset, divisions)

forests = []
for hyper_parameter in hyper_parameters_options:
    forests.append(Forest(hyper_parameter['number_of_trees'],
                          hyper_parameter['number_of_attr_samples']
                          ))

performances = []
for forest in forests:
    performances.append(ModelPerformance())

# para cada possibilidade de divisão do dataset original (Ver Cross Validation)
for i in range(divisions):
    training_set = divisor.get_training_set(i)
    test_set = divisor.get_test_set(i)
    validation_set = divisor.get_validation_set(i)

    # calcular a performance de cada floresta (média e desvio padrão)
    for forest_index in range(len(forests)):
        forest = forests[forest_index]
예제 #26
0
class RFSampler:

	def __init__(self,components,nclasses=2,class_dist=np.array([]),p=0):
		


		'''
		Grow the Forest and store the leaves to compute a function to label the points
		'''

		self.components = map(np.array,components)
		self.p = p
		self.num_components = len(components)
		self.num_nodes = np.array(map(np.prod,components)) + 1 
		self.num_vars = map(len,components)
		self.n = sum(self.num_vars)

		self.forest = Forest(components)
		self.leaves = self.forest.get_leaves()
		self.nleaves = len(self.leaves)
		
		self.cardinalities = np.concatenate([self.components])[0]

		if len(class_dist) == 0:
			self.nclasses = nclasses
			self.classes = ['C%d'%(x) for x in np.arange(1,self.nclasses+1)]
			self.class_dist = class_dist

		else:
			self.class_dist=np.array(class_dist)
			self.nclasses = len(self.class_dist)
			self.classes = ['C%d'%(x) for x in np.arange(1,self.nclasses+1)]
			self.class_limit = np.floor(self.class_dist * self.nleaves)



		'''
		Assign leaves to classes
		
		Currently:
			(1) deterministically switching the classes of the leaves 
			(2) Any number of classes (provided the number is less than the number of leaves)
		'''

		self.label_function = {}
		if len(self.class_dist) == 0:
			counter = 1

			for leaf in self.leaves:
				self.label_function[leaf] = self.classes[np.mod(counter,self.nclasses)]
				counter = counter + 1
		
		else:
			self.class_counts = np.zeros(self.nclasses)
			counter = 0

			for leaf in self.leaves:
				if self.class_counts[ np.mod(counter,self.nclasses)  ] < self.class_limit[np.mod(counter,self.nclasses)]:
					self.label_function[leaf] = self.classes[np.mod(counter,self.nclasses)]
					self.class_counts[np.mod(counter,self.nclasses) ] += 1 
					counter = counter + 1
				else:
					possible_labels, = np.where(self.class_counts < self.class_limit) 
					possible_labels = possible_labels+1
					if(len(possible_labels)>0):
						alternative_label = np.random.choice(possible_labels)
						self.label_function[leaf] = 'C%d'%alternative_label
						self.class_counts[alternative_label-1] += 1 
					else:
						self.label_function[leaf]='C1'
						self.class_counts[0] += 1
					counter = counter + 1


			




	'''
	Method to generate a sample based on the tree
	'''

	def get_sample(self,N,filename):	
		col_names = ['A%d'%(x) for x in np.arange(1,self.n+2)]
		sim_result = pd.DataFrame(index = np.arange(N),columns=col_names)

		for sample_num in np.arange(N):
			
			var_index = 0
			old_value = 0 

			for comp_index in np.arange(self.num_components):

				curr_component = self.forest.get_tree(comp_index)

				new_value = np.random.choice(curr_component[self.forest.roots[comp_index]])
				var_index = var_index + 1 if var_index > 0 else 0
				sim_result.ix[sample_num, var_index  ] = new_value
				old_value = new_value

				
				for i in np.arange(1,self.num_vars[comp_index]):
					var_index = var_index + 1
					new_value = np.random.choice(curr_component[old_value])
					sim_result.ix[sample_num,var_index] = (new_value - (np.sum([np.prod(self.cardinalities[:j]) for j in np.arange(var_index-1)]) +1)) % self.cardinalities[var_index] + 1
					old_value = new_value
			if(np.random.random() < self.p ):
				other_classes = list(set(self.classes) - set(self.label_function[new_value]))
				sim_result.ix[sample_num,self.n] = np.random.choice( other_classes )
			else:
				sim_result.ix[sample_num,self.n] = self.label_function[new_value] 

		sim_result.to_csv(filename,index=False)
예제 #27
0
파일: cntsim.py 프로젝트: davad/cntsim
'''
Created on Jan 17, 2010

@author: sahar
'''
from Bin import Bin
from Node import Node
from Tube import Tube
from Forest import Forest
import math
import numpy as np
import xml.etree.ElementTree as ET

forest = Forest()
forest.initializeGrid()
forest.generateBaseNodes()
forest.addBaseSegments()

def step(dT):
	pass

running = False
while running:
	if segmentNum > MAX_SEGMENTS:
		running = False
	
	

	

예제 #28
0
 def __init__(self, grid_size, design_parameter):
     self.grid_size = grid_size
     self.design_parameter = design_parameter
     self.prob_scale = self.getCharacteristicScale()
     self.norm_const = self.getNormalizationConstant()
     self.forest = Forest(self.grid_size)
예제 #29
0
class HotModel:
    def __init__(self, grid_size, design_parameter):
        self.grid_size = grid_size
        self.design_parameter = design_parameter
        self.prob_scale = self.getCharacteristicScale()
        self.norm_const = self.getNormalizationConstant()
        self.forest = Forest(self.grid_size)

    def getNormalizationConstant(self):
        return ((1 - exp(1 / self.prob_scale)) /
                (1 - exp(-self.grid_size / self.prob_scale)))**2

    def getCharacteristicScale(self):
        return self.grid_size / 10

    def probability(self, location):
        # characteristic scale for the distribution
        l = self.prob_scale
        x = location[0] + 1
        y = location[1] + 1

        return self.norm_const * exp(-x / l) * exp(-y / l)

    def isFullyPopulated(self):
        return self.getNumTrees() >= self.grid_size**2

    def getNumTrees(self):
        return self.forest.getNumTrees()

    def getNormalizedNumTrees(self):
        return self.getNumTrees() / self.grid_size**2

    def getForestYield(self):
        return self.normalizedAverageYieldFrom(self.forest)

    def getForestMatrix(self):
        matrix = np.copy(self.forest.getForestMatrix())
        return matrix

    def getForests(self):
        return self.forest.getForests()

    def normalizedAverageYieldFrom(self, forest):
        return self.averageYieldFrom(forest) / self.grid_size**2

    def averageYieldFrom(self, forest):
        return forest.getNumTrees() - self.averageLightningDamageFrom(forest)

    def averageLightningDamageFrom(self, forest):
        forest_matrix = forest.getForestMatrix()
        damage = 0
        for index, forest_size in np.ndenumerate(forest_matrix):
            loc_prob = self.probability(index)
            damage += forest_size * loc_prob
        return damage

    def addTree(self):
        location = self.getNextTreeLocation()
        self.forest.addTree(location)

    def getNextTreeLocation(self):
        best_location = None
        best_yield = -1

        for location in self.getFutureSearchLocations():
            simulated_forest = self.forest.copy()
            simulated_forest.addTree(location)
            avg_yield = self.averageYieldFrom(simulated_forest)

            if avg_yield > best_yield:
                best_yield = avg_yield
                best_location = location

        if best_location is None:
            raise RuntimeError('Next Tree Location Not Found')

        return best_location

    def getFutureSearchLocations(self):
        possible_locations = self.forest.getUnoccupiedLocations()
        shuffle(possible_locations)

        max_index = min(self.design_parameter, len(possible_locations))
        search_locations = possible_locations[0:max_index]

        return search_locations
예제 #30
0
class World(object):

    def __init__(self, player):
        self.array = []
        self.player = player
        self.c = 0
        self.towns = [Town("Farnfos", [0, 0]), Town("Lunari", [1, 1]),
                      Town("Cewmann", [2, 2]),
                      Town("Caister", [3, 3]), Town("Aramore", [4, 4]),
                      Town("Kilerth", [5, 5]),
                      Town("Eldhams", [6, 6]), Town("Cirrane", [7, 7]),
                      Town("Warcest", [8, 8])]
        self.forest = Forest()

    def menu(self):
        if self.c == 1:
            self.root2.destroy()
        self.c = 0
        self.root = tk.Tk()
        self.array = []
        start = self.player.location
        for i in range(len(self.towns)):
            st = self.towns[i].location
            if math.sqrt((st[0] - start[0]) * (st[0] - start[0]) + (st[1] - start[1]) * (st[1] - start[1])) < 2:
                self.array.append(self.towns[i].name)

        frame = tk.Frame(self.root, bg='#80c1ff', bd=5)
        frame.place(relx=0, rely=0, relwidth=1, relheight=1)

        button = tk.Button(frame, text=self.array[0], command=lambda: self.town(self.array[0]))
        button.place(relx=0, rely=.2 * 0, relwidth=.5, relheight=.1)
        button = tk.Button(frame, text=self.array[1], command=lambda: self.town(self.array[1]))
        button.place(relx=0, rely=.2 * 1, relwidth=.5, relheight=.1)
        button = tk.Button(frame, text=self.array[2], command=lambda: self.town(self.array[2]))
        button.place(relx=0, rely=.2 * 2, relwidth=.5, relheight=.1)

        button = tk.Button(frame, text="forest", command=lambda: self.forrest())
        button.place(relx=0, rely=.2 * 4, relwidth=.5, relheight=.1)
        button = tk.Button(frame, text="Quests", command=lambda: self.quest())
        button.place(relx=0, rely=.2 * 3, relwidth=.5, relheight=.1)
        self.root.mainloop()

    def town(self, name):
        self.root.destroy()
        for i in range(len(self.towns)):
            if name == self.towns[i].name:
                self.player.location = self.towns[int(i)].roads[0].start
                self.towns[int(i)].menu(self.player.location, self.player)
                self.player.location = self.towns[int(i)].location
        self.menu()

    def forrest(self):
        self.root.destroy()
        self.forest.move(self.player, 0)
        self.menu()

    def quest(self):
        self.root.destroy()
        self.c = 1
        self.root2 = tk.Tk()
        frame = tk.Frame(self.root2, bg='#80c1ff', bd=5)
        frame.place(relx=0, rely=0, relwidth=1, relheight=1)
        if len(self.player.quest) > 0:
            for i in range(len(self.player.quest)):
                self.label = tk.Label(frame, text=self.player.quest[i], bg='#80c1ff')
                self.label.place(x=0, y=10 + 20 * i)
            button = tk.Button(frame, text="leave", command=lambda: self.menu())
            button.place(relx=.5, y=10, relwidth=.5, relheight=.1)
        else:
            self.label = tk.Label(frame, text="No Quests", bg='#80c1ff')
            self.label.place(x=0, y=0)
            button = tk.Button(frame, text="leave", command=lambda: self.menu())
            button.place(relx=.5, rely=0, relwidth=.5, relheight=.1)
        self.root2.mainloop()
예제 #31
0
def analyze(file, folds=10):
    """
    Executes the main analysis of a Dataset using the algorithm.
    Reading the dataset from 'file' csv, executes a k-folds Accuracy analyisis,
    with k=folds.
    :param file: File where reading the dataset
    :param folds: K of the k-folds analysis. If -1 then a Leave One Out
    analysis will be performed.
    :return:
    Prints the mean validation accuracy.
    """
    folder = os.path.join('Results', 'dataset-' + file[:-len('.csv')])

    if not os.path.isdir(folder):
        os.makedirs(folder)
    for forest_type, params in experiments.items():
        forest_folder = os.path.join(folder, forest_type)
        if not os.path.isdir(forest_folder):
            os.makedirs(forest_folder)
        acc_matrix = []
        for NT in params['NT']:
            acc_row = [NT]
            for F in params['F']:
                # For each fold
                accuracy = []
                attributes_relevance = []
                for i, (X_train, Y_train, X_val, Y_val, names) in enumerate(
                        get_dataset_k_folds(file=file, k=folds)):
                    M = X_train.shape[-1]
                    # Fit the forest
                    forest = Forest(F=F(M), NT=NT,
                                    forest_type=forest_type).fit(
                                        X=X_train,
                                        Y=Y_train,
                                        X_names=names[:-1])
                    # Predict values for the validation fold
                    predicted = forest.predict(X=X_val, X_names=names[:-1])
                    # Extract the attribute relevance on this forest
                    attributes_relevance.append(forest.attributes_relevance())
                    # Saves the accuracy
                    accuracy.append(100 * np.sum(Y_val == predicted) /
                                    len(Y_val))
                    # Verbose each 20 folds
                    if i % 20 == 0 and i > 0:
                        print(str(i) + " Folds Done")
                accuracy = np.round(np.mean(accuracy), 1)
                print(str(i) + " Folds Executed")
                # Print Results
                print("-" * 50)
                print("Accuracy: " + str(accuracy) + "%")
                acc_row.append(accuracy)
                f_description = str(
                    F(M)) if forest_type == 'random_forest' else str(F(M)())
                forest.save_attributes_relevance_plot(
                    file=os.path.join(forest_folder,
                                      'F-' + f_description + '-NT-' + str(NT)),
                    title=forest_type.replace('_', ' ').title() +
                    ' - Feature Relevance')
            acc_matrix.append(acc_row)
        print(forest_type)
        with open(
                os.path.join(forest_folder,
                             'Acc Matrix ' + str(folds) + '-folds.txt'),
                'w') as f:
            f.write(str(np.array(acc_matrix)))
예제 #32
0
 def build(key):
     if key[0] == "G":
         if len(key) > 1:
             return Grass(key[1])
         else:
             return Grass(None)
     if key[0] == "M":
         if len(key) > 1:
             return Mountain(key[1])
         else:
             return Mountain(None)
     if key[0] == "F":
         if len(key) > 1:
             return Forest(key[1])
         else:
             return Forest(None)
     if key[0] == "W":
         if len(key) > 1:
             return Wall(key[1])
         else:
             return Wall(None)
     if key[0] == "~":
         if len(key) > 1:
             return Water(key[1])
         else:
             return Water(None)
     if key[0] == "S":
         if len(key) > 1:
             return Sand(key[1])
         else:
             return Sand(None)
     if key[0] == "E":
         if len(key) > 1:
             return MetalWall(key[1])
         else:
             return MetalWall(None)
     if key[0] == "T":
         if len(key) > 1:
             return MetalFloor(key[1])
         else:
             return MetalFloor(None)
     if key[0] == "P":
         if len(key) > 1:
             return Plating(key[1])
         else:
             return Plating(None)
     if key[0] == ".":
         if len(key) > 1:
             return Void(key[1])
         else:
             return Void(None)
     if key[0] == "O":
         if len(key) > 1:
             return WoodFloor(key[1])
         else:
             return WoodFloor(None)
     if key[0] == "L":
         if len(key) > 1:
             return WoodFloorDam(key[1])
         else:
             return WoodFloorDam(None)
     if key[0] == "B":
         if len(key) > 1:
             return Bridge(key[1])
         else:
             return Bridge(None)
     if key[0] == "-":
         if len(key) > 1:
             return BridgeTop(key[1])
         else:
             return BridgeTop(None)
     if key[0] == "+":
         if len(key) > 1:
             return BridgeBot(key[1])
         else:
             return BridgeBot(None)
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.init_UI()

    # Setting elements, connections and logic
    def init_UI(self):

        self.FAQ.clicked.connect(self.show_faq)

        self.Generate_button.clicked.connect(self.generate_image_main_logic)

        self.Save_button.setEnabled(False)
        self.Save_button.clicked.connect(self.save_image)

        # base_settings_update connections
        self.base_settings = {'size': 200, 'zoom': 50}
        self.Size_ComboBox.valueChanged.connect(self.base_settings_update)
        self.Zoom_ComboBox.valueChanged.connect(self.base_settings_update)
        # Biomes
        self.Forest = Forest(self.ForestLayout)
        self.Desert = Desert(self.DesertLayout)
        self.Frost = Frost(self.FrostLayout)

    def generate_image_main_logic(self):
        QApplication.setOverrideCursor(Qt.WaitCursor)

        # Generate default noise
        if self.Generation_ComboBox.currentText() == 'Default':
            print('Generated default map')
            self.image = generate_perlin_noise(self.base_settings)
        # Generate forest map
        elif self.Generation_ComboBox.currentText() == 'Forest':
            print('Generated forest map')
            self.image = add_color(generate_perlin_noise(self.base_settings),
                                   self.Forest.get_colors())
        # Generate desert map
        elif self.Generation_ComboBox.currentText() == 'Desert':
            print('Generated desert map')
            self.image = add_color(generate_perlin_noise(self.base_settings),
                                   self.Desert.get_colors())
        # Generate frost map
        elif self.Generation_ComboBox.currentText() == 'Frost':
            print('Generated frost map')
            self.image = add_color(generate_perlin_noise(self.base_settings),
                                   self.Frost.get_colors())

        # Pixmap set
        tmp_img = ImageQt(self.image)
        pixmap = QPixmap.fromImage(tmp_img)
        self.Result.setPixmap(pixmap)
        self.Save_button.setEnabled(True)

        QApplication.restoreOverrideCursor()

    # Save image
    def save_image(self):
        file_name = QFileDialog.getSaveFileName(self, 'Save', '', '*.png')[0]
        if file_name:
            save_file = self.image
            save_file.save(file_name)

    # Updating base_settings dict
    def base_settings_update(self):
        self.base_settings['size'] = self.Size_ComboBox.value()
        self.base_settings['zoom'] = self.Zoom_ComboBox.value()
        print(self.base_settings)

    def show_faq(self):
        self.faq = FAQ()
        self.faq.show()