def __init__(self, alpha): super().__init__(hint_text="Company...", background_color=(0, 0, 0, 0), foreground_color=(1, 1, 1, 1), cursor_color=(0, 1, 0, 1), multiline=False) self.crossRefs = pickle.load(open("res/catDict.p", 'rb')) searchables = list(self.crossRefs.keys()) self.searchRecs = SearchTree(searchables) self.alpha = alpha self.scrollView = None self.searchRecLayout = None self.bind(focus=self.updateAFBox) self.bind(text=self.autofill)
def registerInitialState(self, gameState): CaptureAgent.registerInitialState(self, gameState) self.foodTotal = len(self.getFood(gameState).asList()) self.foodDefendingPrev = self.getFoodYouAreDefending( gameState).asList() self.allyIndex = (self.index + 2) % 4 if self.index < 2: self.side = "Top" else: self.side = "Bottom" self.searchTree = SearchTree() self.foodLost = [] self.patience = 0
def __init__(self, alpha, searchDB): super().__init__(hint_text="Company...", background_color=(0, 0, 0, 0), foreground_color=(1, 1, 1, 1), cursor_color=(0, 1, 0, 1), multiline=False) if not searchDB: searchables = pickle.load(open("res/searchables.p", 'rb')) self.crossRefs = pickle.load(open("res/crossMark6.p", 'rb')) self.searchRecs = SearchTree(searchables) else: self.crossRefs = searchDB[0] self.searchRecs = searchDB[1] self.alpha = alpha self.scrollView = None self.searchRecLayout = None self.bind(focus=self.updateAFBox) self.bind(text=self.autofill)
class SearchBarCompare(TextInput): def __init__(self, alpha): super().__init__(hint_text="Company...", background_color=(0, 0, 0, 0), foreground_color=(1, 1, 1, 1), cursor_color=(0, 1, 0, 1), multiline=False) self.crossRefs = pickle.load(open("res/catDict.p", 'rb')) searchables = list(self.crossRefs.keys()) self.searchRecs = SearchTree(searchables) self.alpha = alpha self.scrollView = None self.searchRecLayout = None self.bind(focus=self.updateAFBox) self.bind(text=self.autofill) def updateAFBox(self, *args): if args[-1]: #print(args) #generateAFBox() self.searchRecLayout = GridLayout(cols=1, size_hint_y=None, height=Window.height * 1) if self.text: self.autofill(self.text) self.alpha.swap(self.searchRecLayout) else: self.alpha.swap() def autofill(self, *args): if self.searchRecLayout and args[-1]: #print("trying to populate") self.searchRecLayout = GridLayout(cols=1, size_hint_y=None, height=Window.height * 1) recommend = self.searchRecs.relateItem(args[-1].upper()) for cat in recommend: #print(r) b = Button(text=cat, height=Window.height * .1, size_hint_max_y=Window.height * .1, size_hint_min_y=Window.height * .1) b.cat = cat def useRec(itself): self.text = itself.cat self.alpha.updateList() b.bind(on_press=useRec) self.searchRecLayout.add_widget(b) self.alpha.swap(self.searchRecLayout)
def __init__(self, master, activity, searchDB=None): #db = (searchables, SearchTree) super().__init__(hint_text="Company...", background_color=(0, 0, 0, 0), foreground_color=(1, 1, 1, 1), cursor_color=(0, 1, 0, 1), multiline=False, size_hint_y=None, size_hint_x=.7, height=Window.height * .1) if not searchDB: searchables = pickle.load(open("res/searchables.p", 'rb')) self.crossRefs = pickle.load(open("res/crossMark6.p", 'rb')) self.searchRecs = SearchTree(searchables) else: self.crossRefs = searchDB[0] self.searchRecs = searchDB[1] self.activity = activity self.master = master self.scrollView = None self.searchRecLayout = None #self.bind(focus = self.updateAFBox) self.bind(text=self.autofill)
def build(self): searchables = pickle.load(open("res/searchables.p", 'rb')) self.crossRefs = pickle.load(open("res/crossMark6.p", 'rb')) self.searchRecs = SearchTree(searchables) self.searchDB = (self.crossRefs, self.searchRecs) self.activities = {"search": SearchActivity(self, self.searchDB)} self.root = GridLayout(cols=1) self.activity = self.activities["search"] ####################################### ############# Scroll View ############# ####################################### self.scrollView = ScrollView(size_hint=(1, None), do_scroll_x=False, do_scroll_y=True, size=(Window.width, Window.height * .9), scroll_timeout=250, y=Window.height * .1) def scrollViewScale(*args): self.scrollView.size = (Window.width, Window.height * .9) self.scrollView.y = Window.height * .1 self.scrollView.bind(size=scrollViewScale) self.scrollView.add_widget(self.activity) self.root.add_widget(self.scrollView) self.activitySelect = ActivitySelect(self) def activitySelectScale(*args): self.activitySelect.size = (Window.width, Window.height * .1) self.activitySelect.y = 0 self.activitySelect.bind(size=activitySelectScale) self.root.add_widget(self.activitySelect) self.currentConduitLabel = "" self.conduit = None Window.bind(on_keyboard=self.androidBack) return self.root
class SearchBar(TextInput): def __init__(self, master, activity, searchDB=None): #db = (searchables, SearchTree) super().__init__(hint_text="Company...", background_color=(0, 0, 0, 0), foreground_color=(1, 1, 1, 1), cursor_color=(0, 1, 0, 1), multiline=False, size_hint_y=None, size_hint_x=.7, height=Window.height * .1) if not searchDB: searchables = pickle.load(open("res/searchables.p", 'rb')) self.crossRefs = pickle.load(open("res/crossMark6.p", 'rb')) self.searchRecs = SearchTree(searchables) else: self.crossRefs = searchDB[0] self.searchRecs = searchDB[1] self.activity = activity self.master = master self.scrollView = None self.searchRecLayout = None #self.bind(focus = self.updateAFBox) self.bind(text=self.autofill) def updateAFBox(self, *args): if args[-1]: self.searchRecLayout = GridLayout(cols=1, size_hint_y=None, height=Window.height * 1) if self.text: self.autofill(self.text) if self.master.searchRecLayout: self.master.remove_widget(self.master.searchRecLayout) self.master.add_widget(self.searchRecLayout) self.master.searchRecLayout = self.searchRecLayout # else: # self.activity.swap() def autofill(self, *args): if args[-1]: self.searchRecLayout = GridLayout(cols=1, size_hint_y=None, height=Window.height * 1) recommend = self.searchRecs.relateItem(args[-1].upper()) txts = [] for r in recommend: cross = "" if r in self.crossRefs: cross = self.crossRefs[r] abbr = cross name = r if len(r) < len(cross) or not cross: abbr = r name = cross elif len(r) == len(cross) and r < cross: abbr = r name = cross if "(the)" in name.lower(): name = "The " + name[0:-6] txt = abbr + ": " + name if txt in txts: continue txts.append(txt) b = Button(text=txt, height=Window.height * .1, halign="center", font_name="res/Aldrich", font_hinting="light", size_hint_max_y=Window.height * .1, size_hint_min_y=Window.height * .1) b.text_size[0] = Window.width b.abbr = abbr b.name = name def useRec(itself): #self.text = itself.abbr self.master.master.portfolio.addStock( itself.abbr, itself.name) self.activity.titleLabel.text = self.master.master.portfolio.name + "'s Stocks" self.activity.swap( PortfolioEditorLayout(self.master.master.portfolio, self.activity)) b.bind(on_press=useRec) self.searchRecLayout.add_widget(b) self.searchRecLayout.height = Window.height * .1 * len(recommend) if self.master.searchRecLayout: self.master.remove_widget(self.master.searchRecLayout) self.master.add_widget(self.searchRecLayout) self.master.searchRecLayout = self.searchRecLayout
class MCTSAgent(CaptureAgent): def registerInitialState(self, gameState): CaptureAgent.registerInitialState(self, gameState) self.foodTotal = len(self.getFood(gameState).asList()) self.foodDefendingPrev = self.getFoodYouAreDefending( gameState).asList() self.allyIndex = (self.index + 2) % 4 if self.index < 2: self.side = "Top" else: self.side = "Bottom" self.searchTree = SearchTree() self.foodLost = [] self.patience = 0 def chooseAction(self, gameState): # start = time.time() myPos = gameState.getAgentState(self.index).getPosition() allyPos = gameState.getAgentState(self.allyIndex).getPosition() foodDefendingNow = self.getFoodYouAreDefending(gameState).asList() foodLost = [ food for food in self.foodDefendingPrev if food not in foodDefendingNow ] _, foodLost = self.isEnemiesNearby(myPos, allyPos, foodLost) if len(foodLost) != 0: self.foodLost = foodLost self.patience = self.getMazeDistance(myPos, foodLost[0]) - 5 if self.patience > 0: self.patience -= 1 else: self.patience = 0 self.foodLost = [] # print self.foodLost, self.patience myState = gameState.getAgentState(self.index) if myState.isPacman: best_action = self.actionAsPacman(gameState) else: best_action = self.actionAsGhost(gameState) self.foodDefendingPrev = foodDefendingNow # print 'eval time for agent %d: %.4f' % (self.index, time.time() - start) return best_action """ ============== Help functions ============== """ def getSuccessor(self, gameState, action): """ Finds the next successor which is a grid position (location tuple). """ successor = gameState.generateSuccessor(self.index, action) pos = successor.getAgentState(self.index).getPosition() if pos != nearestPoint(pos): # Only half a grid position was covered return successor.generateSuccessor(self.index, action) else: return successor def topFoods(self, gameState): foodList = self.getFood(gameState).asList() topFoods = [(x, y) for (x, y) in foodList if y >= gameState.data.layout.height / 2] return topFoods def bottomFoods(self, gameState): foodList = self.getFood(gameState).asList() bottomFoods = [(x, y) for (x, y) in foodList if y < gameState.data.layout.height / 2] return bottomFoods def sideFoods(self, gameState): foodList = [] if self.side == "Top": foodList = self.topFoods(gameState) if len(foodList) == 0: foodList = self.bottomFoods(gameState) else: foodList = self.bottomFoods(gameState) if len(foodList) == 0: foodList = self.topFoods(gameState) return foodList def getBorders(self, gameState): width = gameState.data.layout.width height = gameState.data.layout.height if self.red: return [(width / 2 - 3, h) for h in range(0, height) if (width / 2 - 3, h) not in gameState.data.layout.walls.asList()] else: return [(width / 2 + 2, h) for h in range(0, height) if (width / 2 + 2, h) not in gameState.data.layout.walls.asList()] def getCapsules(self, gameState): if self.red: return gameState.getBlueCapsules() else: return gameState.getRedCapsules() def findClosestFood(self, gameState): bestAction = None minDistance = 1200 for action in gameState.getLegalActions(self.index): successor = self.getSuccessor(gameState, action) myPos = successor.getAgentState(self.index).getPosition() foodList = self.sideFoods(gameState) minDistanceToFood, food = min([(self.getMazeDistance(myPos, food), food) for food in foodList]) if minDistanceToFood < minDistance: minDistance = minDistanceToFood bestAction = action return bestAction, minDistance, food """ ========================= Action decision as Pacman ========================= """ def actionAsPacman(self, gameState): """ Finds an action to take as a pacman. """ myPos = gameState.getAgentState(self.index).getPosition() enemies = [ gameState.getAgentState(i) for i in self.getOpponents(gameState) ] protectorPos = [ a.getPosition() for a in enemies if (not a.isPacman and a.getPosition() != None and a.scaredTimer == 0) ] foodList = self.getFood(gameState).asList() if len(foodList) == 0 or len( self.foodLost) != 0 and gameState.getAgentState( self.index).scaredTimer == 0: return self.searchTree.search(self, gameState, protectorPos, self.findWayBack) isProtectorNear, nearProtectors = self.isProtectorsNearby( gameState, myPos, protectorPos) if not isProtectorNear: return self.actionWithNoDanger(gameState, nearProtectors) else: return self.actionInDanger(gameState, nearProtectors) def isProtectorsNearby(self, gameState, myPos, protectorPos): nearProtectors = [] isProtectorNear = False for protectorPos in protectorPos: distance = self.getMazeDistance(myPos, protectorPos) if distance <= 5: nearProtectors.append(protectorPos) isProtectorNear = True return isProtectorNear, nearProtectors def actionWithNoDanger(self, gameState, nearProtectors): """ Finds an action to take as a pacman when no ghosts have been observed. """ best_action, minDistanceToFood, food = self.findClosestFood(gameState) timeLeft = gameState.data.timeleft / 4 + 1 myPos = gameState.getAgentState(self.index).getPosition() distanceToBorder = min([ self.getMazeDistance(myPos, border) for border in self.getBorders(gameState) ]) distanceFoodToBorder = min([ self.getMazeDistance(food, border) for border in self.getBorders(gameState) ]) carrying = gameState.getAgentState(self.index).numCarrying foodLeft = len(self.getFood(gameState).asList()) if ( minDistanceToFood + distanceFoodToBorder ) >= timeLeft or carrying >= 10 or minDistanceToFood >= distanceToBorder * foodLeft / self.foodTotal and carrying > 0: best_action = self.searchTree.search(self, gameState, nearProtectors, self.findWayBack) return best_action def actionInDanger(self, gameState, nearProtectors): """ Finds an action to take as a pacman when ghosts are nearby. """ timeLeft = gameState.data.timeleft / 4 + 1 capsulesPos = self.getCapsules(gameState) if len(capsulesPos) != 0: best_action = self.searchTree.search(self, gameState, nearProtectors, self.findCapsulesOrWayBack) else: best_action = self.searchTree.search(self, gameState, nearProtectors, self.findWayBack) return best_action def findWayBack(self, gameState, node): disToBorder = min([ self.getMazeDistance(node.myPos, border) for border in self.getBorders(gameState) ]) value = -disToBorder if node.myPos in node.enemiesPos: value = -1000 return value def findCapsulesOrWayBack(self, gameState, node): disToBorder = min([ self.getMazeDistance(node.myPos, border) for border in self.getBorders(gameState) ]) value = -disToBorder if len(node.capsules) != 0: disToCapsule = min([ self.getMazeDistance(node.myPos, capsule) for capsule in node.capsules ]) if disToBorder > disToCapsule: value = -disToCapsule else: value = -disToBorder if node.myPos in node.enemiesPos: value = -1000 return value """ ======================== Action decision as Ghost ======================== """ def actionAsGhost(self, gameState): """ Finds an action to take as a ghost. """ myPos = gameState.getAgentState(self.index).getPosition() allyPos = gameState.getAgentState(self.allyIndex).getPosition() enemies = [ gameState.getAgentState(i) for i in self.getOpponents(gameState) ] invadersPos = [ a.getPosition() for a in enemies if a.isPacman and a.getPosition() != None ] isInvadersNear, nearInvaders = self.isEnemiesNearby( myPos, allyPos, invadersPos) if gameState.getAgentState(self.index).scaredTimer > 0: return self.actionAttack(gameState) elif isInvadersNear: return self.actionWithInvaders(gameState, nearInvaders) elif len(self.foodLost) != 0: return self.actionWithInvaders(gameState, self.foodLost) ghostsPos = [ a.getPosition() for a in enemies if (not a.isPacman and a.getPosition() != None) and a.scaredTimer == 0 ] isGhostsNear, nearGhosts = self.isEnemiesNearby( myPos, allyPos, ghostsPos) if isGhostsNear: return self.actionWithGhosts(gameState, nearGhosts) return self.actionAttack(gameState) def isEnemiesNearby(self, myPos, allyPos, enemiesPos): nearEnemies = [] isEnemiesNear = False for enemyPos in enemiesPos: myDistance = self.getMazeDistance(myPos, enemyPos) allyDistance = self.getMazeDistance(allyPos, enemyPos) if myDistance <= allyDistance: nearEnemies.append(enemyPos) isEnemiesNear = True return isEnemiesNear, nearEnemies def isEnemiesNearbyIndex(self, myPos, allyPos, enermiesStates): nearEnemies = [] isEnemiesNear = False for enermy in enermiesStates: myDistance = self.getMazeDistance(myPos, enermy.getPosition()) allyDistance = self.getMazeDistance(allyPos, enermy.getPosition()) if myDistance <= allyDistance: nearEnemies.append(enermy.index) isEnemiesNear = True return isEnemiesNear, nearEnemies def actionWithInvaders(self, gameState, nearInvaders): bestAction = None minDistance = 1200 # Use Monte Carlo to kill the invader if very close myPos = gameState.getAgentState(self.index).getPosition() enermiesIndex = self.getOpponents(gameState) nearestDistance = 1200 nearestEnermy = 0 for enermy in enermiesIndex: enermyPos = gameState.getAgentPosition(enermy) if enermyPos != None: #print(myPos,enermyPos) if self.getMazeDistance(myPos, enermyPos) < nearestDistance: nearestDistance = self.getMazeDistance(myPos, enermyPos) nearestEnermy = enermy if (self.getMazeDistance(myPos, nearInvader) < 5 for nearInvader in nearInvaders): root = Node(gameState, self.index, nearestEnermy, None, 0, None) root.expand() first_layer_sons = root.sonNodes second_layer_sons = [] third_layer_sons = [] # First Layer triversal/search for node in first_layer_sons: node.triversal() if (node.isEnd == False): node.expand() for son_node in node.sonNodes: second_layer_sons.append(son_node) # Second Layer triversal/search for node in second_layer_sons: node.triversal() if (node.isEnd == False): node.expand() for son_node in node.sonNodes: third_layer_sons.append(son_node) # Third Layer triversal/search for node in third_layer_sons: node.triversal() return root.getBestAction() else: for action in gameState.getLegalActions(self.index): successor = self.getSuccessor(gameState, action) myState = successor.getAgentState(self.index) if myState.isPacman: continue myPos = myState.getPosition() minDistanceToInvaders = min([ self.getMazeDistance(myPos, nearInvader) for nearInvader in nearInvaders ]) if minDistanceToInvaders < minDistance: minDistance = minDistanceToInvaders bestAction = action return bestAction def actionWithGhosts(self, gameState, nearGhosts): bestAction = None minDistance = 1200 borders = self.getBorders(gameState) _, nearestBordersToGhost = min([(self.getMazeDistance(border, ghost), border) for border in borders for ghost in nearGhosts]) for action in gameState.getLegalActions(self.index): successor = self.getSuccessor(gameState, action) myPos = successor.getAgentState(self.index).getPosition() distanceToBorder = self.getMazeDistance(myPos, nearestBordersToGhost) if distanceToBorder < minDistance: minDistance = distanceToBorder bestAction = action return bestAction def actionAttack(self, gameState): foodList = self.sideFoods(gameState) if len(foodList) == 0: return 'Stop' bestAction = None minDistance = 1200 for action in gameState.getLegalActions(self.index): successor = self.getSuccessor(gameState, action) myPos = successor.getAgentState(self.index).getPosition() minDistanceToFood = min( [self.getMazeDistance(myPos, food) for food in foodList]) if minDistanceToFood < minDistance: minDistance = minDistanceToFood bestAction = action return bestAction def findWayFightBack(self, gameState, node): value = 77 disToEnemies = min([ self.getMazeDistance(node.myPos, enemy) for enemy in node.enemiesPos ]) value = -disToEnemies if node.myPos in node.enemiesPos: value = -1000 return value """
class SearchBar(TextInput): def __init__(self, alpha, searchDB): super().__init__(hint_text="Company...", background_color=(0, 0, 0, 0), foreground_color=(1, 1, 1, 1), cursor_color=(0, 1, 0, 1), multiline=False) if not searchDB: searchables = pickle.load(open("res/searchables.p", 'rb')) self.crossRefs = pickle.load(open("res/crossMark6.p", 'rb')) self.searchRecs = SearchTree(searchables) else: self.crossRefs = searchDB[0] self.searchRecs = searchDB[1] self.alpha = alpha self.scrollView = None self.searchRecLayout = None self.bind(focus=self.updateAFBox) self.bind(text=self.autofill) def updateAFBox(self, *args): if args[-1]: self.searchRecLayout = GridLayout(cols=1, size_hint_y=None, height=Window.height * 1) if self.text: self.autofill(self.text) self.alpha.swap(self.searchRecLayout) # else: # self.alpha.swap() def autofill(self, *args): if self.searchRecLayout and args[-1]: self.searchRecLayout = GridLayout(cols=1, size_hint_y=None, height=Window.height * 1) recommend = self.searchRecs.relateItem(args[-1].upper()) txts = [] for r in recommend: cross = "" if r in self.crossRefs: cross = self.crossRefs[r] abbr = cross name = r if len(r) < len(cross) or not cross: abbr = r name = cross elif len(r) == len(cross) and r < cross: abbr = r name = cross if "(the)" in name.lower(): name = "The " + name[0:-6] txt = abbr + ": " + name if txt in txts: continue txts.append(txt) b = Button(text=txt, height=Window.height * .1, halign="center", font_name="res/Aldrich", font_hinting="light", size_hint_max_y=Window.height * .1, size_hint_min_y=Window.height * .1) b.text_size[0] = Window.width b.abbr = abbr def useRec(itself): self.text = itself.abbr self.alpha.swap() self.alpha.updateLoader() b.bind(on_press=useRec) self.searchRecLayout.add_widget(b) self.searchRecLayout.height = Window.height * .1 * len(recommend) self.alpha.swap(self.searchRecLayout)
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2020/9/25 20:13 # Author: Zheng Shaoxiang # @Email : [email protected] # Description: # 一维装箱问题(One-dimensional bin packing problem, 1D-BPP)问题的 # 分支定价算法(Branch and Price, BP) from instance import Instance import basicmodel from searchTree import SearchTree import cProfile if __name__ == '__main__': instance = Instance() # 读取文件生成1D-BPP实例 print(f"{instance=}") bp = basicmodel.BinPacking({item.id: item for item in instance.items}, instance.capacity) m = bp.solve() # bp.print_variables() print(f"{m.Runtime=}\t{m.objVal=}") print(f"-" * 60) tree = SearchTree(instance, verbose=True) # 初始化搜索树 tree.solve() # cProfile.run('tree.solve()', sort=1)