def prompt_user_for_positions(): """get list of positions 'quit' or ctrl+c exits""" positions = [] while True: try: positions_input = input("List of positions?") # Raises a ValueError and loops back if user_input is not # a sequence of powers of 10 separated by commas positions = Position.get_position_list(positions_input) num_trials_input = input("num trials?") num_trials = Position.get_integer_if_possible(num_trials_input) break except KeyboardInterrupt: # Exit if the user enters Ctrl+C sys.exit(0) except EOFError: # Exit if the user enters Ctrl+D sys.exit(0) except ValueError: print("Invalid list of positions") return positions, num_trials
def main() : """Reads a list of positions and the number of trials from the user and outputs statistics to results.txt and histogram_####_pos.pdf""" try : resFile = open('results.txt','w') #Fixed bias at .51 as specified in the assigment bias = .51 #Expects a comma-delimited list of numbers inp = input("Give a list of positions (comma-separated, e.g., 1, 5, 10): ") positions = [int(x) for x in inp.split(",")] numTrials = int(input("Give the number of trials (integer at least 1): ")) for p in positions : position = Position(p,numTrials,bias) position.computeAllTrials() resFile.write("Position = %d, Mean = %f, Std = %f\n"%(p,position.getMean(),position.getStd())) plt.figure() plt.hist(position.daily_ret,100,range=[-1,1]) plt.xlabel('Daily Returns') plt.ylabel('Trials') plt.title('Histogram of Daily Returns') plt.savefig("histogram_%04d_pos.pdf" % p) resFile.close() except IOError as ioerr : print("Error with file: %s" % ioerr) except PositionError as perr: print("PositionError: %s" % perr) return except ValueError : print('Error in input!') return
def test_computeAllTrials2(self) : """Tests computeAllTrials with bias = 0, and tests getMean and getStd""" p = Position(2,100,0) p.computeAllTrials() self.assertEqual(p.cumu_ret[1],0) np.testing.assert_almost_equal(p.daily_ret[1],-1,decimal=7) np.testing.assert_almost_equal(p.getMean(),-1,decimal=7) np.testing.assert_almost_equal(p.getStd(),0,decimal=7)
def test_computeTrial1(self) : """Tests computeTrial with bias = 1""" p = Position(2,2,1) p.computeTrial(0) self.assertEqual(p.cumu_ret[0],2000) np.testing.assert_almost_equal(p.daily_ret[0],1,decimal=7) p.computeTrial(1) self.assertEqual(p.cumu_ret[1],2000) np.testing.assert_almost_equal(p.daily_ret[1],1,decimal=7)
def startUp(): random.seed() running = True armLeft = Position.position(0,"") armRight = Position.position(0,"") back = Position.position(0,"") backpack = [] back.equip("backpack") for i in range(12): backpack.append(Position.position(0,"")) Player = Human.Human(raw_input("Enter your character's name: "),input("Enter your character's age: "),input("Is your character 1) male 2) female?"),50,3,200,5)
def accelerate(self, goal): factor = -1.01 difference = Position( factor*(self.position.x-goal.x), factor*(self.position.y-goal.y), factor*(self.position.z-goal.z) ) self.velocity.renormalize(MAX_VELOCITY) if difference.length() <= MAX_VELOCITY: # initiate docking procedures? #sell shit? pass #difference = difference.renormalize(1.0) self.velocity.x += difference.x self.velocity.y += difference.y self.velocity.z += difference.z
def is_proper_block(block): """ Check whether the given block is a proper block. - True if and only if the set of dot positions of the given block is not empty, if each of its elements is a proper position, and if the dot positions of the given block are chained together. ASSUMPTIONS: - None """ if type(block) is not _Block or len(block.dots) == 0: return False for pos in block.dots: if not Position.is_proper_position(pos): return False return Position.are_chained(block.dots)
def test_Is_Proper_Position__Improper_Second_Element(score, max_score): """Function is_proper_position: given position is a tuple of length 2 with non-integer as second element.""" max_score.value += 1 try: if Position.is_proper_position(("a", 0)): return if Position.is_proper_position(("a", -1)): return if Position.is_proper_position(("a", "b")): return if Position.is_proper_position((3, [1])): return score.value += 1 except: pass
def test_Up__Position_In_Range(score, max_score): """Function up: resulting position in range""" max_score.value += 1 try: if Position.up((6, 8), ("c", 6)) != ("d", 6): return if Position.up((6, 8), ("b", 6), 3) != ("e", 6): return if Position.up((6, 9), ("e", 8)) != ("X", 8): return if Position.up((10, 10), ("e", 2), 5) != ("X", 2): return score.value += 1 except: pass
def remove_block_from(board, block): """ Remove the given block from the given board. - No other blocks change their position as a result of removing the given block. - Nothing happens if the given block is not loaded on the given board. ASSUMPTIONS - The given board is a proper board. - The given block is a proper block. """ if contains_block(board, block): position = get_leftmost_position_of(board, block) for i in range(Block.get_length(block)): del board[Position.get_row(position)][Position.get_column(position) + i]
def test_Get_Adjacent_Positions__Edge_Positions(score, max_score): """Function get_adjacent_positions: edge positions""" max_score.value += 2 try: adjacent_positions = Position.get_adjacent_positions((1, 3), 8) assert adjacent_positions == {(1, 4), (1, 2), (2, 3)} adjacent_positions = Position.get_adjacent_positions((8, 3), 8) assert adjacent_positions == {(8, 4), (8, 2), (7, 3)} adjacent_positions = Position.get_adjacent_positions((3, 1), 8) assert adjacent_positions == {(2, 1), (4, 1), (3, 2)} adjacent_positions = Position.get_adjacent_positions((3, 8), 8) assert adjacent_positions == {(2, 8), (4, 8), (3, 7)} score.value += 2 except: print(traceback.format_exc())
def add_block_at(board, block, position): """ Add the given block at the given position on the given board. - If the given position is equal to (r,c), the given block will occupy the cells (r,c), (r,c+1), ..., (r,c+L-1) on the given board, in which L denotes the length of the given block. ASSUMPTIONS - The given board is a proper board. - The given block is a proper block. - The given position is a proper position. - The given board can accept the given block at the given position. """ for i in range(Block.get_length(block)): board[Position.get_row(position)][Position.get_column(position) + i] = block
def _generate_random_posns(self, map): """ Generates a random pair of symmetric positions such that the positions do not conflict with any object in the map and returns the pair. """ max_ = map.size - 1 while True: x = randint(0, max_ / 3) y = randint(0, max_ / 3) posn1 = Position(x, y, max_, max_) posn2 = Position(max_ - x, max_ - y, max_, max_) if (map.get_symbol(posn1) == EMPTY and map.get_symbol(posn2) == EMPTY): break return [posn1, posn2]
def test_Get_Adjacent_Positions__Corner_Positions(score, max_score): """Function get_adjacent_positions: corner positions""" max_score.value += 2 try: adjacent_positions = Position.get_adjacent_positions((1, 1), 8) assert adjacent_positions == {(1, 2), (2, 1)} adjacent_positions = Position.get_adjacent_positions((1, 8), 8) assert adjacent_positions == {(1, 7), (2, 8)} adjacent_positions = Position.get_adjacent_positions((8, 1), 8) assert adjacent_positions == {(7, 1), (8, 2)} adjacent_positions = Position.get_adjacent_positions((8, 8), 8) assert adjacent_positions == {(7, 8), (8, 7)} score.value += 2 except: pass
def __init__(self, LENGTH, seed): self._possibleDirections = [ Position.Position(-1, 0), Position.Position(1, 0), Position.Position(0, -1), Position.Position(0, 1) ] self._LENGTH = LENGTH self._tiles = [[Tile.Tile for i in range(self._LENGTH)] for j in range(self._LENGTH)] self._tilesVistited = [] self._previousTiles = [] self._builder = Position.Position(0, 0) self._seed = seed random.seed(self._seed)
def test_Get_Surrounding_Positions__Corner_Positions(score, max_score): """Function get_surrounding_positions: corner positions""" max_score.value += 2 try: surrounding_positions = Position.get_surrounding_positions((1, 1), 8) assert surrounding_positions == {(1, 2), (2, 2), (2, 1)} surrounding_positions = Position.get_surrounding_positions((1, 8), 8) assert surrounding_positions == {(1, 7), (2, 7), (2, 8)} surrounding_positions = Position.get_surrounding_positions((8, 1), 8) assert surrounding_positions == {(7, 1), (7, 2), (8, 2)} surrounding_positions = Position.get_surrounding_positions((8, 8), 8) assert surrounding_positions == {(7, 8), (7, 7), (8, 7)} score.value += 2 except: pass
def get_length_horizontal_chain(board, position, State_count=None): """ Return the length of the horizontal chain of disks involving the given position. Zero is returned if no disk is stored at the given position. ASSUMPTIONS - The given board is a proper board and the given position is a proper position for the given board. """ disk_column_position = Position.column(position) row = position[1] row_board_position = dimension(board) - (row - 1) disks = [] if get_disk_at(board, position) == None: return 0 row_in_board = board[row_board_position] Dict_disk = {} for disk_position in range(len(row_in_board)): disk = row_in_board[disk_position] if Disk.is_proper_disk(dimension(board), disk): disks.append(disk) Dict_disk.update({disk_position + 1: disk}) State_count = True if disk == None and State_count == True: if disk_column_position in Dict_disk.keys(): return len(disks) else: State_count = None disks = [] return len(disks)
def are_chainable(board, positions, chained=None, nextpos=None, is_filled=None): """ Check whether the given collection of positions is chained on the given board. - True if and only if at least one collection of chained positions exists on the given board that includes all given positions and for which all the cells in that collection are either all filled or all empty. ASSUMPTIONS - The given board is a proper board. - Each of the given positions is a proper position for the given board. - All the cells on the given board at the given positions all have the same state, i.e. they are all filled or all empty. NOTE - This function should be worked out in a recursive way """ if chained is None: chained = set() for nextpos in positions: is_filled = nextpos in board.dots break else: return True for adjpos in Position.get_adjacent_positions(nextpos, board.dimension): if (adjpos in board.dots) == is_filled and adjpos not in chained: chained.add(adjpos) if not (set(positions) - chained) or are_chainable(board, positions, chained, adjpos, is_filled): return True return not (set(positions) - chained)
def get(self, bot): while len(bot.possible_pawn_actions) > 0: possible_pawn_positions = bot.possible_pawn_actions # ignore previous moves if len(possible_pawn_positions) > 1: previous_moves = bot.pawn_moves_previous possible_pawn_positions = [ m for m in possible_pawn_positions if m not in previous_moves ] pos_next = Position(possible_pawn_positions[0].line, possible_pawn_positions[0].column) fn_cost = self.get_fn_cost(bot) fn_property = self.get_fn_position_property(bot) goal = bot.pos_goal cost_to_beat = fn_property(pos_next) - fn_property(goal) for move in possible_pawn_positions: potential_new_cost = fn_property(move) - fn_property(goal) print('Cost to beat is {}, potential new cost {} ({})'.format( cost_to_beat, potential_new_cost, move)) if fn_cost(potential_new_cost, cost_to_beat): cost_to_beat = potential_new_cost pos_next = move print('New cost to beat {}, pos_next is {}'.format( potential_new_cost, pos_next)) yield GameMovePawn(pos_next)
def formatTarget(rawTarget, apidMap): tInfoMap = {} for bssid in rawTarget: if int(bssid, 16) not in apidMap.bssid2Apid: continue tInfoMap[apidMap.getApid(bssid)] = TargetInfo(rawTarget[bssid], True) return Target(0, Position(0, 0), tInfoMap)
def play(self, percepts, player, step, time_left): self.player = player self.board = dict_to_board(percepts) self.actions = list(self.board.get_actions(player)) # is our first move self.pos_current = self.get_current_position() self.pos_goal = self.find_goal() if step <= len(self.board.pawns): self.pos_starting = self.pos_current self.goal_direction = self.get_goal_direction() self.init_strategies() self.possible_pawn_actions = self.get_possible_pawn_positions() print('--------------------------------') print( 'Step: {}, player: {}, player move: {}\nat: {}, goal: {}, goal direction: {}' .format(step, self.player, self.player_move, self.pos_current, self.pos_goal, self.goal_direction)) # print('horiz_walls on board: {}'.format(self.board.horiz_walls)) # print('verti_walls on board: {}'.format(self.board.verti_walls)) # print('possible pawn moves: {}'.format([m.__str__() for m in self.get_possible_pawn_positions()])) print('Pawn moves to date: {}'.format( [m.__str__() for m in self.pawn_moves_previous])) if step == 101: return GameMoveEnd().to_game_format() for m in self.move_generator: if m.is_pawn_move(): self.pawn_moves_previous.append(Position(m.line, m.column)) print('Next move: {}'.format(m)) self.player_move += 1 return m.to_game_format() print('No more move to do. END GAME.') return GameMoveEnd().to_game_format()
def testFlotte_nbBatCoule3(): flot = Flotte() pos = Position(8, 7) bat = Bateau(1, 0, pos) flot.ajouterBateau(bat) flot.bateaux()[0].touchePosition(pos) return flot.nbBatCoule == 1
def handleCollisions(globs): room = globs.dungeon[globs.player.pos.roomnum] checkItems(globs, room) rt = False if globs.trap == 1: globs.floor += 1 rt = True elif globs.trap == 2: globs.floor -= 1 rt = True if rt: globs.dungeon = Dungeon.genDungeon() globs.player.pos = Position.Position(0, 2, 1) globs.trap = 0 Enemy.genEnemies(globs) return room = checkDoors(globs, room) if globs.player.pos.x < 1: globs.player.pos.x += 1 elif globs.player.pos.x > room.width - 2: globs.player.pos.x -= 1 elif globs.player.pos.y < 1: globs.player.pos.y += 1 elif globs.player.pos.y > room.height: globs.player.pos.y -= 1
def testFlotte_flotteDetruite(): flot = Flotte() pos = Position(8, 7) bat = Bateau(1, 0, pos) flot.ajouterBateau(bat) flot.bateaux()[0].touchePosition(pos) return flot.flotteDetruite()
def __init__(self, name = 'robot', color = 'red'): self.name = name self.color = color self.actions = [] self.start_zone = None self.pos = Position() # x,y,theta,speed,acceleration self.current_action = None
def testPosition(): nb_test_pos = 6 nb_test_pos_reussi = 0 # Tests constructeur if (testPos_creerMauvaisePositionX()): # doit retourner une erreur nb_test_pos_reussi += 1 else: print "Echec test : position incorrecte en X, elle n'aurait pas dû être créée" if (testPos_creerMauvaisePositionY()): # doit retourner une erreur nb_test_pos_reussi += 1 else: print "Echec test : position incorrecte en Y, elle n'aurait pas dû être créée" pos = Position(3, 7) if testPos_x(): nb_test_pos_reussi += 1 if testPos_y(): nb_test_pos_reussi += 1 if testPos_touche(): nb_test_pos_reussi += 1 if testPos_devientTouche(): nb_test_pos_reussi += 1 return ((float)(nb_test_pos_reussi) / (float)(nb_test_pos)) * 100
def readTargetFile(targetFilePath, apidMap): targets = [] f = open(targetFilePath, 'r+') for line in f.readlines(): line = line.replace('\r', '').replace('\n', '').replace(':', ',') if len(line) == 0: continue columns = line.split(' ') # require at least 3 dimensions (APs or beacons) if len(columns) < 4: continue # x, y values = columns[0].split(',') x = float(values[0]) y = float(values[1]) pos = Position(x, y) # ap tInfoMap = {} for column in columns[1:]: if len(column) == 0: continue values = column.split(',') bssid = values[0].upper() apid = apidMap.getApid(bssid) level = float(values[1]) tInfoMap[apid] = TargetInfo(level, True) targets.append(Target(len(targets), pos, tInfoMap)) f.close() return targets
def testPos_creerMauvaisePositionY(): try: pos2 = Position(5, 100) except Exception: return True else: return False
def readReferFile(referFilePath, apidMap): refers = [] f = open(referFilePath, 'r+') for line in f.readlines(): line = line.replace('\r', '').replace('\n', '').replace(':', ',') if len(line) == 0: continue columns = line.split(' ') # require at least 3 dimensions (APs or beacons) if len(columns) < 4: continue # x, y values = columns[0].split(',') x = float(values[0]) y = float(values[1]) pos = Position(x, y) # ap rInfoMap = {} for column in columns[1:]: if len(column) == 0: continue values = column.split(',') bssid = values[0].upper() apid = apidMap.getApid(bssid) mean = float(values[1]) std = float(values[2]) rInfoMap[apid] = ReferInfo(mean, std) refers.append(Refer(len(refers), pos, rInfoMap)) f.close() return refers
def crossTiles(self, pos, nextMove): self._tiles[pos.getY()][pos.getX()].removeWall(nextMove) invertedPos = Position.Position(nextMove.getX() * -1, nextMove.getY() * -1) self._tiles[pos.getY() + nextMove.getY()][pos.getX() + nextMove.getX()].removeWall(invertedPos)
def testBateau(): nb_test_bat = 8 nb_test_bat_reussi = 0 pos = Position(3, 7) # Tests constructeur bat = Bateau(2, 2, pos) if testBat_creerBateauMauvaiseTaille(): nb_test_bat_reussi += 1 else: print "Echec test : Le bateau a été créée alors que la taille n'est pas comprise entre 0 et 4 " if testBat_creerBateauMauvaisePosition(): nb_test_bat_reussi += 1 else: print "Echec test : Le bateau n'aurait pas du être créer (dépassement de grille)" if testBat_creerBateauMauvaiseDirection(): nb_test_bat_reussi += 1 else: print "Echec test : Le bateau a été créée alors que la direction n'est pas comprise entre 0 et 3" if testBat_taille(): nb_test_bat_reussi += 1 if testBat_positions(): nb_test_bat_reussi += 1 if testBat_nbPosTouche(): nb_test_bat_reussi += 1 if testBat_touchePosition(): nb_test_bat_reussi += 1 if testBat_estCoule(): nb_test_bat_reussi += 1 return ((float)(nb_test_bat_reussi) / (float)(nb_test_bat)) * 100
def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.x = x self.y = y self.position = Position.Position(self.x, self.y) self.image = tower1[0] self.rect = self.image.get_rect() self.rect.center = (self.position.x + 50, self.position.y + 50) self.damage = 0 self.range = 150 self.reload_ms = 500 self.maxReload_ms = self.reload_ms self.hitbox = (self.position.x, self.position.y, self.image.get_width(), self.image.get_height()) self.time = 0 self.diff_ms = 0 self.prev_ms = 0 self.isFullAmmo = True self.isMenuVisible = False self.upgradeRect = upgrade.get_rect() self.sellRect = upgrade.get_rect() self.replaceRect = upgrade.get_rect() self.upgradeCount = 0 self.upgradeCost = (50, 80, 120) self.extaDamage = (25, 30, 60) self.startTimer = False self.timer = 0 self.label = None self.type = 0 self.maxUpgraded = False
def do_explosions(board, current_step=None): """ Removes all disks that satisfy the condition to explode at the moment the function is invoked and activates all adjactant positions. This creates a new situation on the board. The function then does the explosions in the next step(in the new situation). The function keeps repeating this until there are no more disks that satisfy the condition to explode. - The function returns the score obtained from all explosions that occured. """ if not current_step: current_step = 1 all_positions_to_explode = Board.get_all_positions_to_explode(board) score_current_step = len( all_positions_to_explode) * score_step_1**current_step if all_positions_to_explode == frozenset(): return 0 all_positions_to_activate = Position.get_all_adjacent_positions( Board.dimension(board), all_positions_to_explode) Board.crack_disks_at(board, all_positions_to_activate) Board.remove_all_disks_at(board, all_positions_to_explode) return score_current_step + do_explosions(board, current_step + 1)
def addPosition(self, position, parent): pos = self.searchPosition(position) if pos is not None: raise InvalidArgument(position + " has already been created") elif self.positionTree is None: newPos = Position(position) self.positionTree = Node(newPos) elif parent is None: raise InvalidArgument("Root can be only one") else: par = self.searchPosition(parent) if par is None: raise InvalidArgument(parent + " does not exist") else: newPos = Position(position) Node(newPos, par)
def testFlotte_verifTir1(): flot = Flotte() pos = Position(8, 7) bat = Bateau(1, 0, pos) flot.ajouterBateau(bat) # Bateau 0 touché return flot.verifTir(pos)[0] == 1 and flot.verifTir(pos)[1] == 0
def __loadConfigs(self, config_path, print_configs=False): # Load yaml and return a dictionary configYaml = loadYaml(config_path) # UAV Position self.position = Position() self.position.x = configYaml["start_position"]["x"] self.position.y = configYaml["start_position"]["y"] self.position.z = configYaml["start_position"]["z"] self.position.heading = configYaml["start_position"]["heading"] # Topic Names self.odometryTopic = configYaml["topics"]["odometry"] self.cameraTopic = configYaml["topics"]["camera"] self.poseTopic = configYaml["topics"]["pose"] # UAV Publishers self.posePublisher = rospy.Publisher(self.poseTopic, PoseStamped, queue_size=10) # UAV Name self.uavName = configYaml["uav_name"] # Used to debug config informations if (print_configs): rospy.logwarn("UAV Position: (%.2f, %.2f, %.2f, %.3f)", self.position.x, self.position.y, self.position.z, self.position.heading) rospy.logwarn("UAV odometryTopic: %r", self.odometryTopic) rospy.logwarn("UAV cameraTopic: %r", self.cameraTopic) rospy.logwarn("UAV poseTopic: %r", self.poseTopic) rospy.logwarn("UAV posePublisher: %r", self.posePublisher)
def find_goal(self): board_goal = self.board.goals[self.player][0] # player 0 and 1 are NORTH and SOUTH if self.player < 2: return Position(board_goal, self.pos_current.column) print('Unknown player index... Cannot resolve goal') return None
class Robot: """robot class, performs actions in the game, actions that take time""" def __init__(self, name = 'robot', color = 'red'): self.name = name self.color = color self.actions = [] self.start_zone = None self.pos = Position() # x,y,theta,speed,acceleration self.current_action = None def can_take(self, item): return False def orient_to(self, point): next_angle = self.pos.angle_to(point) def move(self, distance): next_point = self.pos.get_point_at_dist(distance)
def get_move (self, updates, map, first_move = False) : """ Gets the move from the bot. Sets the curr_position accordingly. """ direction = self.bot.get_move (updates, first_move) self.prev_posn = Position (self.curr_posn.x, self.curr_posn.y, self.curr_posn.max_x, self.curr_posn.max_y) self.curr_posn.update (direction) self.put_trail_for_html (map)
def __init__ (self, symbol, starting_posn, code_file) : """ Initializes the bike. """ self.curr_posn = starting_posn self.prev_posn = Position (starting_posn.x, starting_posn.y, starting_posn.max_x, starting_posn.max_y) self.symbol = symbol self.bot = Bot (symbol, code_file) self.is_dead = False
def __init__( self, domaine, positionNid, b0, b1 ): self.domaine = domaine self.position = Position( positionNid.x, positionNid.y ) self.positionNid = Position( positionNid.x, positionNid.y ) self.mode = 0 # Parametres de calcul des probabilites de mouvement self.s0 = 1.0 self.s1 = 0.01 self.b0 = b0 self.b1 = b1
def __init__(self, sublocale, ObjectType): self.sdc = 1 self.mdc = 0 self.sublocale = sublocale self.storage_capcity = 0 self.storage_space = 0 self.active = True self.position = Position(rand() * 1000.0, rand() * 1000.0, rand() * 10.0) self.velocity = Position(0.0, 0.0, 0.0) self.oldsector = 0 self.mass = 1.0 self.objectType = ObjectType if ObjectType=='GroovyEffect': sublocale.effects.append(self) if ObjectType=='Vehicle': sublocale.vehicles.append(self) if ObjectType=='Resource': sublocale.resources.append(self) if ObjectType=='Structure': sublocale.structures.append(self)
class Fourmi: domaine = None # Un objet de type Domaine qui gere les taux de # pheromones dans l'environnement de la fourmi # et les positions des sources de nouriture. position = None # Position de la fourmi positionNid = None # Position du nid de fourmis mode = 0 # mode = 0 Cherche de la nouriture # mode = 1 Rapporte la nouriture au nid # Parametres pour le calcul des probalite de deplacement des fourmis s0 = 1.0 s1 = 0.01 b0 = 1 b1 = 8 # Quantite de pheromones emises a chaque seconde emission_pheromones = 1. # Constante des mouvements en fonction de la case choisie ... # 0 1 2 # 3 O 4 # 5 6 7 mouvement_x = [-1,0,1,-1,1,-1,0,1] mouvement_y = [-1,-1,-1,0,0,1,1,1] # Offsets accocies aux 8 cellules entourrant la fourmi delta_distances_x = array([ [-1,0,1],[-1,0,1],[-1,0,1] ]) delta_distances_y = array([ [-1,-1,-1],[0,0,0],[1,1,1] ]) # Quantite totale de nourriture amassee par toutes les fourmis total_nouriture = 0 # Constructeur de la classe Fourmi # Initialisation de toutes les variables internes de l'objet au # moment de sa creation. # # domaine Un objet de type Domaine qui gere les taux de # pheromones dans l'environnement de la fourmi et les # positions des sources de nouriture. # positionNid Position en X et en Y du nid de fourmis def __init__( self, domaine, positionNid, b0, b1 ): self.domaine = domaine self.position = Position( positionNid.x, positionNid.y ) self.positionNid = Position( positionNid.x, positionNid.y ) self.mode = 0 # Parametres de calcul des probabilites de mouvement self.s0 = 1.0 self.s1 = 0.01 self.b0 = b0 self.b1 = b1 # Commande a la fourmi de se deplacer en fonction du taux de pheromones # ou en fonction de l'emplacement de son nid. def bouge( self ): # Demande les taux de pheromone au domaine local = self.domaine.environnementLocal( self.position ) # Cree la matrice des probabilites de mouvement ... P = zeros( (3,3), float ) # On boucle pour remplir la matrice des probabilites for j in range(3): for i in range(3): # On saute la case centrale if( i == 1 and j == 1 ): continue # Action differente en fonction du mode if( self.mode == 0 ): # Probabilites de mouvement en fonction # des pheromones P[j][i] = (local[i][j] + self.s0 )**self.b0 else: # On calcul les probabilites pour # retourner au nid x = self.position.x + self.delta_distances_x[j][i] y = self.position.y + self.delta_distances_y[j][i] position_cellule = Position(x,y) distance_du_nid = position_cellule.distance( self.positionNid ) P[j][i] = 1./(distance_du_nid + 1. + self.s1 )**self.b1 # Maintenant on normalise les probalites ... somme = sum(sum( P )) for j in range(3): for i in range(3): if( somme == 0 ): P[i][j] = 1./8. else: P[i][j] /= somme # On convertit les probabilites en une liste de 8 elements P = reshape( P, (1,9) ).tolist()[0] del P[4] # DEBUG # if( self.mode == 1 ): # string_P = "" # for i in range(len(P)): # string_P += "%0.6f "%P[i] # print string_P # Fait la somme cumulative des probabilites ... # La derniere cellule doit contenir 1. for i in range(1,len(P)): P[i] += P[i-1] # Nous avons notre vecteur de probabilites ... r = Random().random() # Choix au hasard pour prendre la decision de la direction index = 0 for i in range(len(P)): if( r < P[i] ): index = i break; # DEBUG # if( self.mode == 0 ): # print index # print self.mouvement_x[index] # print self.mouvement_y[index] # On deplace la fourmie self.position.x += self.mouvement_x[index] self.position.y += self.mouvement_y[index] # Verifie les conditions aux limites if( self.position.x < 1 ): self.position.x = 1 if( self.position.x > self.domaine.nx-2 ): self.position.x = self.domaine.nx-2 if( self.position.y < 1 ): self.position.y = 1 if( self.position.y > self.domaine.ny-2 ): self.position.y = self.domaine.ny-2 # Demande a la fourmi d'emetre des pheromones dans le domaine a la # position qu'elle occupe. def modifieEnvironnement( self ): # Si on cherche de la nourriture et qu'on en trouve ... if( self.mode == 0 and self.domaine.contientNouriture( self.position ) ): self.mode = 1 # ...ou si on en a deja et qu'on emet des pheromones ... elif( self.mode == 1 ): self.domaine.ajoutePheromones( self.position, self.emission_pheromones ) # ou qu'on arrive au nid ... if( self.position.equals( self.positionNid ) ): self.mode = 0 Fourmi.total_nouriture += 1
# Objet de gestion du parametre de source source = SourceSansEffet(0) # Domaine dans lequel evoluent la fourmi domaine = Domaine( lx, ly, dx, dt, source, hg, bd, 0.02, 10. ) domaine.n[4][4] = 1 domaine.n[5][4] = 2 domaine.n[6][4] = 3 domaine.n[4][5] = 4 domaine.n[5][5] = 0 domaine.n[6][5] = 5 domaine.n[4][6] = 6 domaine.n[5][6] = 7 domaine.n[6][6] = 8 # Une fourmi fourmi = Fourmi( domaine, position_du_nid, 1, 1 ) fourmi.bouge() fourmi = Fourmi( domaine, position_du_nid, 1, 1 ) fourmi.mode = 1 fourmi.positionNid = Position(5,3) fourmi.bouge() p1 = Position(5,4) p2 = Position(5,3) print p1.distance(p2)
def test_computeTrial2(self) : """Tests computeTrial with bias = 0""" p = Position(2,2,0) p.computeTrial(0) self.assertEqual(p.cumu_ret[0],0) np.testing.assert_almost_equal(p.daily_ret[0],-1,decimal=7)
def bouge( self ): # Demande les taux de pheromone au domaine local = self.domaine.environnementLocal( self.position ) # Cree la matrice des probabilites de mouvement ... P = zeros( (3,3), float ) # On boucle pour remplir la matrice des probabilites for j in range(3): for i in range(3): # On saute la case centrale if( i == 1 and j == 1 ): continue # Action differente en fonction du mode if( self.mode == 0 ): # Probabilites de mouvement en fonction # des pheromones P[j][i] = (local[i][j] + self.s0 )**self.b0 else: # On calcul les probabilites pour # retourner au nid x = self.position.x + self.delta_distances_x[j][i] y = self.position.y + self.delta_distances_y[j][i] position_cellule = Position(x,y) distance_du_nid = position_cellule.distance( self.positionNid ) P[j][i] = 1./(distance_du_nid + 1. + self.s1 )**self.b1 # Maintenant on normalise les probalites ... somme = sum(sum( P )) for j in range(3): for i in range(3): if( somme == 0 ): P[i][j] = 1./8. else: P[i][j] /= somme # On convertit les probabilites en une liste de 8 elements P = reshape( P, (1,9) ).tolist()[0] del P[4] # DEBUG # if( self.mode == 1 ): # string_P = "" # for i in range(len(P)): # string_P += "%0.6f "%P[i] # print string_P # Fait la somme cumulative des probabilites ... # La derniere cellule doit contenir 1. for i in range(1,len(P)): P[i] += P[i-1] # Nous avons notre vecteur de probabilites ... r = Random().random() # Choix au hasard pour prendre la decision de la direction index = 0 for i in range(len(P)): if( r < P[i] ): index = i break; # DEBUG # if( self.mode == 0 ): # print index # print self.mouvement_x[index] # print self.mouvement_y[index] # On deplace la fourmie self.position.x += self.mouvement_x[index] self.position.y += self.mouvement_y[index] # Verifie les conditions aux limites if( self.position.x < 1 ): self.position.x = 1 if( self.position.x > self.domaine.nx-2 ): self.position.x = self.domaine.nx-2 if( self.position.y < 1 ): self.position.y = 1 if( self.position.y > self.domaine.ny-2 ): self.position.y = self.domaine.ny-2
positions = [] while True: try: positions_input = input("List of positions?") # Raises a ValueError and loops back if user_input is not # a sequence of powers of 10 separated by commas positions = Position.get_position_list(positions_input) num_trials_input = input("num trials?") num_trials = Position.get_integer_if_possible(num_trials_input) break except KeyboardInterrupt: # Exit if the user enters Ctrl+C sys.exit(0) except EOFError: # Exit if the user enters Ctrl+D sys.exit(0) except ValueError: print("Invalid list of positions") return positions, num_trials if __name__ == '__main__': """collect user input about investment options, then evaluate how they perform over a day's random outcomes and store results to file""" positions, num_trials = prompt_user_for_positions() Position.process_one_day(positions = positions, num_trials = num_trials)
# type: (Position, Position, int, int) -> None """ Cuboid class initialization :param start: Position :param end: Position :param material: int :param material_modification: int :rtype: None """ mc.setBlocks(start.x, start.y, start.z, end.x, end.y, end.z, material, material_modification) if __name__ == "__main__": # direct call for testing purpose # self test code # od = Position.relative_distance ( 2 , 2 , -1 ) do = Position.relative_distance(4, 2, 1) Cuboid(Position.relative_distance(2, 1, -1), do, 1, 0) Position.origin() pos = Position() pos.rotate_left() Cuboid(Position(pos, 4, 1, -1), Position(pos, 7, 2, 1), 1, 0) pos.rotate_right() pos.rotate_right() Cuboid(Position(pos, 4, 1, -1), Position(pos, 8, 2, 1), 1, 0) pos.rotate_right() Cuboid(Position(pos, 4, 1, -1), Position(pos, 9, 2, 1), 1, 0)
class WorldObject: def __init__(self, sublocale, ObjectType): self.sdc = 1 self.mdc = 0 self.sublocale = sublocale self.storage_capcity = 0 self.storage_space = 0 self.active = True self.position = Position(rand() * 1000.0, rand() * 1000.0, rand() * 10.0) self.velocity = Position(0.0, 0.0, 0.0) self.oldsector = 0 self.mass = 1.0 self.objectType = ObjectType if ObjectType=='GroovyEffect': sublocale.effects.append(self) if ObjectType=='Vehicle': sublocale.vehicles.append(self) if ObjectType=='Resource': sublocale.resources.append(self) if ObjectType=='Structure': sublocale.structures.append(self) def RedoSector(self, oldsector): try: #print dir(oldsector.vehicles) self.oldsector.vehicles.remove(self) #oldsector.structures.remove(self) except: pass #print '.', self.oldsector = Locale.getOnly().getSectorFromXY(self.position.x,self.position.y) def checkSector(self): oldsector = self.oldsector if oldsector == 0: self.RedoSector(oldsector) return if self.position.x < 0.0: self.position.x += 1000.0 self.RedoSector(oldsector) if self.position.y < 0.0: self.position.y += 1000.0 self.RedoSector(oldsector) if self.position.x > 1000.0: self.position.x -= 1000.0 self.RedoSector(oldsector) if self.position.y > 1000.0: self.position.y -= 1000.0 self.RedoSector(oldsector) def idle(self, deltaT): if not self.active: return self.position.x += self.velocity.x * deltaT; self.position.y += self.velocity.y * deltaT; self.position.z += self.velocity.z * deltaT; self.oldsector = 0 # sandbox.getSectorFromXY(self.position.x, self.position.y) self.checkSector() # only need to call this occasionally.. optimize later def expire(self): self.active = False def takeDamage(self, sdc, mdc): # structural & mega-damage capacity if mdc > 0.0: self.mdc -= mdc if self.mdc < 0.0: self.expire() def accelerate(self, goal): factor = -1.01 difference = Position( factor*(self.position.x-goal.x), factor*(self.position.y-goal.y), factor*(self.position.z-goal.z) ) self.velocity.renormalize(MAX_VELOCITY) if difference.length() <= MAX_VELOCITY: # initiate docking procedures? #sell shit? pass #difference = difference.renormalize(1.0) self.velocity.x += difference.x self.velocity.y += difference.y self.velocity.z += difference.z
import pprint from Base import * from Position import * import StockfighterAPI import json import Databaser account = 'FIB53708038' venue = 'MBPEX' ticker = 'BFC' # INITIALISE VARIABLES pos = Position(venue, account, ticker) base_url = pos.base_url api_key = pos.api_key venue = pos.venue account = pos.account print('some') print('some') print('some') # callback function - probs def tickertape_message(m): value_list = [] try: if m.is_text: msg = json.loads(m.data.decode('utf-8'))
class Bike : """ Represents the bike in arena. """ def __init__ (self, symbol, starting_posn, code_file) : """ Initializes the bike. """ self.curr_posn = starting_posn self.prev_posn = Position (starting_posn.x, starting_posn.y, starting_posn.max_x, starting_posn.max_y) self.symbol = symbol self.bot = Bot (symbol, code_file) self.is_dead = False def __str__ (self) : """ For pretty printing the object. """ return ("Current Position : " + self.curr_posn.__str__ () + linesep + "Previous Position : " + self.prev_posn.__str__ () + linesep + "Symbol : " + symbol + linesep) def put_trail_for_html (self, map) : """ The function which reports a different symbol for the trail for the visualizer purposes. """ if self.symbol == BIKE_1_SYMBOL : trail_symbol = TRAIL1 else : trail_symbol = TRAIL2 map.log_updates (self.prev_posn.x, self.prev_posn.y, map.get_symbol (self.prev_posn), trail_symbol) def get_move (self, updates, map, first_move = False) : """ Gets the move from the bot. Sets the curr_position accordingly. """ direction = self.bot.get_move (updates, first_move) self.prev_posn = Position (self.curr_posn.x, self.curr_posn.y, self.curr_posn.max_x, self.curr_posn.max_y) self.curr_posn.update (direction) self.put_trail_for_html (map) def power_up (self, arena, power_symbol) : """ Take appropriate actions depending on the Power up symbol. """ if power_symbol == RESET : # if the map cell is a bot symbol and not the head of the trail # ie, not the current position of the bike itself, delete all the map_size = arena.map.size for i in range (map_size) : for j in range (map_size) : position = Position (i, j, map_size, map_size) if (arena.map.get_symbol (position) in [BIKE_1_SYMBOL, BIKE_2_SYMBOL] and (arena.bikes[0].curr_posn != position) and (arena.bikes[1].curr_posn != position)) : arena.map.set_symbol (position, EMPTY) elif power_symbol == TRAVERSER : self.bot.traverser_left += TRAVERSER_CAPACITY + 1 # The + 1 is necessary because later, during this move, # it is going to be decreased by 1. elif power_symbol == NITRO : self.bot.nitro_left += NITRO_QUANTITY + 1