def get_next_move(self, coordstring): #I am Player One. Only return one coordinate if(coordstring[0:1]=='D'): move = random.choice(list(self.__moves)) self.__moves.discard(move) print move, "jjj" return str(move.get_msg_repr()) #I am Player two, this is my first move. if(coordstring[0:1]=='L'): self.__moves.discard(Coord(coordstring[1:3],coordstring[3:5])) self.__moves.discard(Coord(coordstring[5:7],coordstring[7:9])) #Regular Case else: self.__moves.discard(Coord(coordstring[0:2],coordstring[2:4])) self.__moves.discard(Coord(coordstring[4:6],coordstring[6:8])) move1 = random.choice(list(self.__moves)) self.__moves.discard(move1) move2 = random.choice(list(self.__moves)) self.__moves.discard(move2) returnvalue = str(move1.get_msg_repr()+move2.get_msg_repr()) return returnvalue
def printValidMoves(g: Game, c: Coord): moves = g.getValidMoves(c) b = g.board print(Style.BRIGHT, end="") if g.turn == 1: print(Fore.RED + " > Black <", g.getScore(), Fore.RESET) else: print(Fore.RED + " Black ", g.getScore(), Fore.RESET) print(" a b c d e f g h") print(" " + "▄" * 18) for y in range(len(b)): print(f"{8-y} █", end="") for x in range(len(b[y])): print(Back.LIGHTBLACK_EX if (x + y) % 2 == 1 else Back.BLACK, end="") if (Coord(x, y) in moves): print(Back.LIGHTMAGENTA_EX, end="") elif (Coord(x, y) == c): print(Back.LIGHTCYAN_EX, end="") if (b[y][x].team == 1): print(Fore.RED, end="") elif (b[y][x].team == 0): print(Fore.BLUE, end="") print(chooseSprite(b[y][x]), end=" ") print(Back.RESET + Fore.RESET, end="") print("█") print(" " + "▀" * 18) if g.turn == 0: print(Fore.BLUE + " > White <", g.getScore(), Fore.RESET) else: print(Fore.BLUE + " White ", g.getScore(), Fore.RESET) print(Style.RESET_ALL, end="")
def test_gamemanager(level2): gm = GameManager() player_names = [] for i in range(3): player_names.append("bruh " + str(i)) gm.register_player_names(player_names) assert len(gm.players) == 3 assert gm.players[0].name == "bruh 0" assert gm.players[1].name == "bruh 1" assert gm.players[2].name == "bruh 2" gm.start_game(level2) assert gm.gamestate.current_level assert len(gm.players) == 3 assert len(gm.gamestate.players) == 3 assert gm.players[0].name == "bruh 0" assert gm.players[1].name == "bruh 1" assert gm.players[2].name == "bruh 2" new_player_locs = [gm.players[0].pos, gm.players[1].pos, gm.players[2].pos] new_player_locs[2] = Coord(7, 18) gm.request_player_move(gm.players[2].name, Coord(7, 3)) assert gm.players[2].pos == Coord(7, 3) item = Item(KEY, Coord(8, 17)) gm.apply_player_item_interaction(gm.gamestate.players[2], Coord(8, 17)) print(str(gm.gamestate.players[2])) assert item in gm.gamestate.players[2].inventory
def test_reachable_tiles_multiple(room1): coord = Coord(8, 7) tiles = room1.get_reachable_tiles(coord) assert len(tiles) == 3 assert Coord(8, 6) in tiles assert Coord(8, 8) in tiles assert Coord(9, 7) in tiles
def test_invalid_level_dimensions(capsys, level1): invalid_dimensions = Room(Coord(6, 1), Coord(6, 6), tiles, doors) level1.rooms.append(invalid_dimensions) valid_level = check_level(level1) capture = capsys.readouterr() assert capture.out == 'Invalid Level: Overlapping Room(s) or Hallway(s)\n' assert valid_level == False
def _find_coord(self, s): _p = s.split() for x in _p: r = re_coord1.search(x) if r: p = r.group(0).replace("-", " ").replace(":", " ").replace( ",", "").replace(".", "").split() return (s.replace(r.group(0), "").strip(), Coord(p[0].replace("x", "X").replace("y", "Y"), p[1], p[2])) for x in _p: r = re_coord2.search(x) if r: p = r.group(0).replace("-", " ").replace(":", " ").replace( ",", "").replace(".", "").split() return (s.replace(r.group(0), "").strip(), Coord(p[0].replace("x", "X").replace("y", "Y"), p[1], int(p[1]) + 1)) for x in _p: r = re_coord3.search(x) if r: c = r.group(0).replace("x", "X").replace("y", "Y") return (s.replace(r.group(0), "").strip(), Coord(c, 0, chrom_lengths[self.assembly][c])) return (s, None)
def generate_pacman_and_cherries(self): free_cells = [ pos for pos, cell in self.grid.cells.items() if pos.x != self.grid.width // 2 and cell.is_floor() ] self.random.shuffle(free_cells) left_cells = [ pos for pos in free_cells if pos.x < self.grid.width // 2 ] i = 0 while i < self.pacman_per_player: left_cell = Coord(left_cells[i].x, left_cells[i].y) right_cell = Coord(self.grid.width - 1 - left_cell.x, left_cell.y) left_player = self.random.randint(0, 1) right_player = (left_player + 1) % 2 self.players[left_player][i] = left_cell self.players[right_player][i] = right_cell i += 1 for j in range(self.cherries // 2): left_cell = Coord(left_cells[i + j].x, left_cells[i + j].y) right_cell = Coord(self.grid.width - 1 - left_cell.x, left_cell.y) self.grid.get(left_cell).has_cherry = True self.grid.get(right_cell).has_cherry = True players = set() for player in self.players: for pos in player: players.add(pos) for pos, cell in self.grid.cells.items(): if cell.is_floor() and not cell.has_cherry and pos not in players: cell.has_pellet = True
def walk(instructions): """ >>> walk("R2, L3") (5, None) >>> walk("R2, R2, R2") (2, None) >>> walk("R5, L5, R5, R3") (12, None) >>> walk("R8, R4, R4, R8") (8, 4) """ position = BlockCoord(0, 0) heading = Coord(0, 1) visited = set((position, )) part2 = None for instruction in instructions.strip().split(', '): if instruction[0] == 'R': heading = heading.rotate_right() elif instruction[0] == 'L': heading = heading.rotate_left() for step in range(int(instruction[1:])): position += heading if part2 is None and position in visited: part2 = position visited.add(position) return (position.distance_blocks(), part2.distance_blocks() if part2 else None)
def get_reachable_tiles(self, coord): try: tiles = [] is_horizontal = self.check_orientation() # If halls should be 1 tile wide any traversable coord in a horizontal hall must have the same y value as a door. The range of traversable tiles spans the x boundary while y does not change if is_horizontal == True: col_values = set() for room in self.rooms: for door in room.doors: col_values.add(door.col) for ii in range(self.origin.row, self.origin.row + self.dimensions.row + 1): if coord.col in col_values: new_coord = Coord(ii, coord.col) tiles.append(new_coord) elif is_horizontal == False: row_values = set() for room in self.rooms: for door in room.doors: row_values.add(door.row) for jj in range(self.origin.col, self.origin.col + self.dimensions.col + 1): if coord.row in row_values: new_coord = Coord(coord.row, jj) tiles.append(new_coord) return tiles except Exception as err: print(err) return None
def create(cls, arr, height=None, width=None, chart_id=None, index=None, pixels=None, orientation=0, mirror=(False, False)): obj = cls() obj.arr = np.array(arr, dtype=Chart.DATA_TYPE, copy=True) obj.chart_id = chart_id if height == None: obj.height = obj.arr.shape[0] else: obj.height = height if width == None: obj.width = obj.arr.shape[1] else: obj.width = width if index != None: obj.index = Coord(index) obj.low = Coord(index[0], index[1]) obj.high = Coord(index[0] + height, index[1] + width) if pixels == None: obj.pixels = obj._count_pixels() else: obj.pixels = pixels if orientation < 0 or orientation > 3: raise Exception('Invalid orientation in Chart.create') obj.orientation = orientation return obj
def next_best_point(st, bot=None): minX = bot.region["minX"] maxX = bot.region["maxX"] minZ = bot.region["minZ"] maxZ = bot.region["maxZ"] # print(bot.region) for y, x, z in np.transpose( np.where( np.transpose(st.matrix._ndarray, (1, 0, 2)) == state.Voxel.MODEL)): if minX <= x < maxX and minZ <= z < maxZ: coord = Coord(int(x), int(y), int(z)) if st.matrix.would_be_grounded(coord): # print(coord) return coord for y, x, z in np.transpose( np.where( np.transpose(st.matrix._ndarray, (1, 0, 2)) == state.Voxel.MODEL)): if minX - (maxX - minX) / 2 <= x < maxX + (maxX - minX) / 2 and minZ - ( maxZ - minZ) / 2 <= z < maxZ + (maxZ - minZ) / 2: coord = Coord(int(x), int(y), int(z)) if st.matrix.would_be_grounded(coord): # print(coord) return coord return None
def handle_keys(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == KEYDOWN: pass elif event.type == KEYUP: pass elif event.type == MOUSEBUTTONDOWN: print(self.plan_map) print('BUTTON:', event.button) x, y = event.pos if event.button == 1: if self.first_vertex: self.plan_map.firstV.x = x self.plan_map.firstV.y = y self.first_vertex = not self.first_vertex elif self.nearest_edge is None: self.plan_map.split_edge(self.plan_map.lastE, Coord(x, y)) else: self.plan_map.split_edge(self.nearest_edge, Coord(x, y)) elif event.button == 3: nearest_edge = self.plan_map.nearest_edge(Coord(x, y)) print('Nearest edge:', nearest_edge)
def post(self): headers = request.headers game_id = headers["game"] if (game_id not in manager.games.keys()): return {"error": "game not in game manager"} g = manager.getGame(game_id) if (headers["action"] == "move"): fromC = Coord(headers["x1"], headers["y1"]) toC = Coord(headers["x2"], headers["y2"]) try: g.makeMove(fromC, toC) db.child("Games").child(game_id).set( toJson(manager.games[game_id])) return {"done": True} except Exception as e: return { "error": "error at moving, message included.", "message": str(e) } if (headers["action"] == "getMoves"): fromC = Coord(headers["x1"], headers["y1"]) try: valids = g.getValidMoves(fromC) except Exception as e: return {"error": str(e)} print([str(c) for c in valids]) out = {"coords": []} # ind = 0 for c in valids: out["coords"].append({"x": c.x, "y": c.y}) # ind+=1 return out g.debugPrint()
def parse_room_obj(room_input): try: room_json = json.loads(room_input) except TypeError: room_json = room_input origin = None bounds = None layout = None point = None try: # [Room, Point] format if room_json[0][TYPE] != ROOM: print('Invalid Args: Type is not room') return None input_json = room_json[0] point = room_json[1] except (KeyError, IndexError): input_json = room_json origin = input_json[ORIGIN] bounds = input_json[BOUNDS] layout = input_json[LAYOUT] origin_coord = to_coord(origin) dimensions = Coord(bounds[ROWS], bounds[COLS]) tiles = [] doors = [] for ii in range(0, bounds[ROWS]): for jj in range(0, bounds[COLS]): # ii = x jj = y if layout[ii][jj] != 0: tiles.append(Coord(origin[0] + ii, origin[1] + jj)) if layout[ii][jj] == 2: doors.append(Coord(origin[0] + ii, origin[1] + jj)) return {COORD: to_coord(point) if point else None, ROOM: Room(origin_coord, dimensions, tiles, doors)}
def aStar(mapCells, srcX, srcY, dstX, dstY): openSet = [] closedSet = [] startNode = Node(mapCells, srcX, srcY, dstX, dstY, None) openSet.append(startNode) while len(openSet) != 0: curCandidate = getLowestScoreNode(openSet) if curCandidate.x == dstX and curCandidate.y == dstY: #then success! path = [] curNode = curCandidate while not (curNode.x == srcX and curNode.y == srcY): coord = Coord(curNode.x, curNode.y) path.append(coord) curNode = curNode.prev # we also add this last one coord = Coord(curNode.x, curNode.y) path.append(coord) path.reverse() return path openSet.remove(curCandidate) closedSet.append(curCandidate) # add this node's neighbors to the open list addNeighbors(curCandidate, openSet, closedSet, mapCells, dstX, dstY) print "oh no!"
def printPossibleMoves(g: Game, c: Coord): moves = g.getPossibleMoves(c) b = g.board print(Style.BRIGHT, end="") print(Fore.RED + " Black " + Fore.RESET) print(" 0 1 2 3 4 5 6 7") print(" " + "▄" * 18) for y in range(len(b)): print(f"{y} █", end="") for x in range(len(b[y])): print(Back.LIGHTBLACK_EX if (x + y) % 2 == 1 else Back.BLACK, end="") if (Coord(x, y) in moves): print(Back.LIGHTMAGENTA_EX, end="") elif (Coord(x, y) == c): print(Back.LIGHTCYAN_EX, end="") if (b[y][x].team == 1): print(Fore.RED, end="") elif (b[y][x].team == 0): print(Fore.BLUE, end="") print(chooseSprite(b[y][x]), end=" ") print(Back.RESET + Fore.RESET, end="") print("█") print(" " + "▀" * 18) print(Fore.BLUE + " White " + Fore.RESET) print(Style.RESET_ALL, end="")
def get_cardinal_coords(cur_pos): up = Coord(cur_pos.row - 1, cur_pos.col) down = Coord(cur_pos.row + 1, cur_pos.col) left = Coord(cur_pos.row, cur_pos.col - 1) right = Coord(cur_pos.row, cur_pos.col + 1) directions = [up, down, left, right] return directions
def maxSlices(pizza): matrix = pizza.grid print "matrix:" print matrix # Output Data Type slices = [] iMax = pizza.R jMax = pizza.C i = 0 while (i < (iMax - 1)): j = 0 while (j < (jMax - 1)): startVal = matrix[i][j] endVal = matrix[i][j + 1] if (isValidSlice(startVal, endVal)): startCoord = Coord(i, j) endCoord = Coord(i, j + 1) currSlice = Slice(startCoord, endCoord) slices.append(currSlice) j += 2 else: j += 1 i += 1 # print matrix for currSlice in slices: currSlice.printSlice() visitSlices(matrix, slices)
def _inverse_kinematics(self, target): """Calculate the necessary angle for a target, in the YZ plane. Uses the circle intersection method.""" # Circle Centers c0 = Coord(0, -BASE_RADIUS, 0); c1 = Coord(0, target.y - EFFECTOR_RADIUS, target.z); # Distance between both circles dist = c0.get_abs_distance(c1); # Cirle radius r0 = BICEP_LENGTH; r1 = math.sqrt(FOREARM_LENGTH**2 - target.x**2) + JOINT_OFFSET; # Check valid distance between the two if 0 >= dist or dist > r0 + r1: print "Invalid position - Potentially outside of reach" # raise Exception(); # Calculate middle point a = (r0**2 - r1**2 + dist**2) / (2 * dist); # Calculate the angle and return new_angle = 180 * (math.atan2(c1.z, -c1.y + c0.y) + math.acos(a/r0)) / math.pi; print "Calculated Angle: ", new_angle; return new_angle;
def get_vision(self, direction: Snake.Direction, pos: Coord, cherry: Coord): vision = list() r_pos = Coord(pos.x, pos.y) adj = [(-1, 0), (0, -1), (1, 0)] for i in range(direction.value): adj = [(-y, x) for x, y in adj] r_pos.x, r_pos.y = -r_pos.y, r_pos.x x, y = (cherry - r_pos).get_unit_vector().get() if x == 0: vision += [0, 0, 0] if y == -1 else [1, 0, 0] elif x == 1: if y == 0: vision += [0, 1, 0] else: vision += [0, 0, 1] if y == -1 else [0, 1, 1] elif x == -1: if y == 0: vision += [1, 1, 0] else: vision += [1, 1, 1] if y == -1 else [1, 0, 1] for vector in adj: last = pos + vector if last not in self.cells or self.cells[last].is_wall(): vision.append(1) elif self.cells[last].has_body: vision.append(1) elif self.cells[last].has_cherry: vision.append(0) else: vision.append(0) return vision
def part2(program): screen = {} score = None last_ball_x = 0 last_paddle_x = 0 def paddle_ai(): return (last_ball_x > last_paddle_x) - (last_ball_x < last_paddle_x) computer = Computer(program, mem_override={0: 2}, input=paddle_ai) computer.input_func = paddle_ai while not computer.halted: try: x = computer.run() y = computer.run() pos = Coord(x, y) if pos == Coord(-1, 0): score = computer.run() else: screen[pos] = computer.run() if screen[pos] == 3: last_paddle_x = pos.x if screen[pos] == 4: last_ball_x = pos.x except Halted: pass return score
def test_coord(): c1 = Coord(0, 0) c2 = Coord(0, 1) c3 = Coord(0, 0) assert c1 != c2 assert c2 != c3 assert c1 == c3
def gen_ref(self, tx, wall_type, wall_pos): distance = 0 if wall_type == "top" or wall_type == "bottom": distance = wall_pos - tx.y return Coord(tx.x, tx.y + 2 * distance), wall_type else: distance = wall_pos - tx.x return Coord(tx.x + 2 * distance, tx.y), wall_type
def make_ray(dim, base, _dir): dim = Coord(dim) coord = Coord(base) _dir = Coord(_dir) result = [] while inside(coord.reset(coord + _dir), dim): result.append(coord.dat) return result
def test_invalid_level_shared_coords(capsys, room1, level1): hall = Hallway([Coord(5, 15), Coord(10, 20)], [room1, room2]) level1.hallways[0] = hall valid_level = check_level(level1) capture = capsys.readouterr() # assert capture.out == 'Invalid Level: Hallway or Room sharing coordinates\n' # TODO: Fix hallway to be valid assert valid_level == False
def generate_diagonal_moves(piece: BasePiece, all_pieces: Iterable[BasePiece], repeat: bool = True): return generate_offset_moves( piece, all_pieces, (Coord(1, -1), Coord(-1, 1), Coord(1, 1), Coord(-1, -1)), repeat, )
def generate_straight_moves(piece: BasePiece, all_pieces: Iterable[BasePiece], repeat: bool = True): return generate_offset_moves( piece, all_pieces, (Coord(1, 0), Coord(-1, 0), Coord(0, 1), Coord(0, -1)), repeat, )
def __init__(self, x, y, vx, vy, car_type='normal', attack_type=None): self.id = next(self.id_generator) self.position = Coord(x, y) self.speed = Coord(vx, vy) self.type = car_type self.generate_xpath() self.generate_ypath() self.attack_type = attack_type self.network = None
def shortest_path_algo(st): bot = st.bots[0] bot.smove(UP) minX, maxX, minY, maxY, minZ, maxZ = st.matrix.bounds print(st.matrix.bounds) minarea, maxbots = 6 * 6, 20 width, depth = maxX - minX, maxZ - minZ mostarea = width * depth / maxbots rsize = ceil(sqrt(max(mostarea, minarea))) xbots, zbots = max(floor(width / rsize), 1), max(floor(depth / rsize), 1) nbots = xbots * zbots print("nbots: {}".format(nbots)) regions = [] for x in range(xbots): rX = min([maxX, minX + (x + 1) * rsize]) if maxX - rX < rsize: rX = maxX for z in range(zbots): rZ = min([maxZ, minZ + (z + 1) * rsize]) if maxZ - rZ < rsize: rZ = maxZ region = { "minX": int(minX + x * rsize), "maxX": int(rX), "minZ": int(minZ + z * rsize), "maxZ": int(rZ) } print(region) regions.append(region) # print(convex_hull(st)) # print(st.matrix.bounds) st.step_all() for i in range(1, nbots): # print(st.bots[0].seeds) sorted(st.bots, key=lambda bot: -len(bot.seeds))[0].fission(FORWARD, 0) st.step_all() b = st.bots[i] b.region = regions[nbots - i - 1] path = shortest_path(st, b, Coord(b.region["minX"], 1, b.region["minZ"])) if path: compress(st, b, path) st.step_all() b = st.bots[0] b.region = regions[nbots - 1] path = shortest_path(st, b, Coord(b.region["minX"], 1, b.region["minZ"])) if path: compress(st, b, path) st.step_all() solve(st) print("finished solve") st.step_all()
def get_introns(self): """Returns a list of coordinates that represent the introns for this transcript""" introns = [] for i in range(len(self.exons) - 1): ex1 = self.exons[i] ex2 = self.exons[i + 1] if self.strand == -1: intron = Coord(self.chrom, ex2.end + 1, ex1.start - 1, strand=self.strand) else: intron = Coord(self.chrom, ex1.end + 1, ex2.start - 1, strand=self.strand) intron.exon_5p = ex1 intron.exon_3p = ex2 introns.append(intron) if self.intron_scores is not None: intron.score = self.intron_scores[i] if self.known_intron_flags is not None: if self.known_intron_flags[i] == "1": intron.is_known = True else: intron.is_known = False return introns
def test_basic_matrix(self): m = Matrix(problem=1) c = Coord(8, 9, 10) self.assertTrue(m[c].is_void()) m[c].set_full() self.assertTrue(m[c].is_full()) self.assertFalse(m[c].is_grounded()) m.yplane(9)[8, 10].set_grounded() self.assertTrue(m[c].is_grounded()) self.assertTrue(m[Coord(13, 5, 8)].is_model())
def add_target(self, random=True, set_location=Coord(0, 0)): if random == True: self.target_coords.append( Coord(randint(0, self.x - 1), randint(0, self.y - 1))) self.num_targets += 1 self.total_targets += 1 else: self.target_coords.append(set_location) self.num_targets += 1 self.total_targets += 1 self.target_set = True
def get_introns(self): """Returns a list of coordinates that represent the introns for this transcript""" introns = [] for i in range(len(self.exons)-1): ex1 = self.exons[i] ex2 = self.exons[i+1] if self.strand == -1: intron = Coord(self.chrom, ex2.end+1, ex1.start-1, strand=self.strand) else: intron = Coord(self.chrom, ex1.end+1, ex2.start-1, strand=self.strand) intron.exon_5p = ex1 intron.exon_3p = ex2 introns.append(intron) if self.intron_scores is not None: intron.score = self.intron_scores[i] if self.known_intron_flags is not None: if self.known_intron_flags[i] == "1": intron.is_known = True else: intron.is_known = False return introns
def from_element(cls, rtept, namespace): name = rtept.findtext('{%s}name' % namespace).encode('utf_8') lat = float(rtept.get('lat')) lon = float(rtept.get('lon')) ele_tag = rtept.find('{%s}ele' % namespace) ele = 0 if ele_tag is None else int(ele_tag.text) time_text = rtept.findtext('{%s}time' % namespace) dt = datetime.strptime(time_text, GPX_DATETIME_FORMAT) coord = Coord.deg(lat, lon, ele, dt) return cls(name, coord)
def track(self): ele = 'ele' if any(b.ele for b in self.b) else 'alt' coords = [Coord.deg(b.lat, b.lon, getattr(b, ele), b.dt) for b in self.b] kwargs = {} kwargs['filename'] = os.path.basename(self.filename) if 'plt' in self.h and not NOT_SET_RE.match(self.h['plt']): kwargs['pilot_name'] = self.h['plt'].strip() if 'gty' in self.h and not NOT_SET_RE.match(self.h['gty']): kwargs['glider_type'] = self.h['gty'].strip() if 'gid' in self.h and not NOT_SET_RE.match(self.h['gid']): kwargs['glider_id'] = self.h['gid'].strip() for k in self.i.keys(): if any(getattr(b, k) for b in self.b): kwargs[k] = [getattr(b, k) for b in self.b] if self.c: tps = [Turnpoint(c.name, Coord.deg(c.lat, c.lon, 0), 0) for c in self.c] kwargs['declaration'] = Task('Declaration', tps) return track.Track(coords, **kwargs)
def interpolate(self, *vecs, **kwargs): """Interpolate the function at given points. The points are either provided as a large array with each row consisting of one point or as a tuple of vectors each defining one coordinate of the interpolation points. If `as_grid` is True, each combination of coordinates will be used (each point on the grid defined by the coordinates). Additional keyword args are passed to scipy.interpolate.interpn. TODO: write up properly""" as_grid = kwargs.get('as_grid', False) if as_grid: coo = Coord(*vecs) vecs = coo.asarr() method = kwargs.get('method', 'linear') bounds_error = kwargs.get('bounds_error', False) fill_value = kwargs.get('fill_value', 0.0) return interpn(self.coord.vecs, self.fvals, vecs, method=method, bounds_error=bounds_error, fill_value=fill_value)
def track(self): ele = 'ele' if any(b.ele for b in self.b) else 'alt' coords = [Coord.deg(b.lat, b.lon, getattr(b, ele), b.dt) for b in self.b] kwargs = {} kwargs['filename'] = os.path.basename(self.filename) if 'plt' in self.h and not NOT_SET_RE.match(self.h['plt']): kwargs['pilot_name'] = self.h['plt'].strip() if 'gty' in self.h and not NOT_SET_RE.match(self.h['gty']): kwargs['glider_type'] = self.h['gty'].strip() if 'gid' in self.h and not NOT_SET_RE.match(self.h['gid']): kwargs['glider_id'] = self.h['gid'].strip() for k in self.i.keys(): if any(getattr(b, k) for b in self.b): kwargs[k] = [getattr(b, k) for b in self.b] return track.Track(coords, **kwargs)
def from_element(cls, element, namespace): name = element.findtext("{%s}name" % namespace).encode("utf_8") desc_tag = element.find("{%s}desc" % namespace) desc = None if desc_tag is None else desc_tag.text.encode("utf_8") lat = float(element.get("lat")) lon = float(element.get("lon")) ele_tag = element.find("{%s}ele" % namespace) ele = 0 if ele_tag is None else int(ele_tag.text) time_tag = element.find("{%s}time" % namespace) if time_tag is None: dt = None else: dt = datetime.datetime.strptime(time_tag.text, GPX_DATETIME_FORMAT) coord = Coord.deg(lat, lon, ele, dt) radius_tag = element.find("{%s}extensions/{%s}radius" % (namespace, namespace)) radius = 400 if radius_tag is None else int(radius_tag.text) enter = element.find("{%s}extensions/{%s}exit" % (namespace, namespace)) is None return cls(name, coord, radius, enter, desc)
def __init__(self, url, path=None): self.url = url components = urlparse.urlparse(self.url) self.name = os.path.splitext(os.path.basename(components.path))[0] if path: file = open(path) else: file = urllib2.urlopen(self.url) if file.info().typeheader != 'image/jpeg': raise RuntimeError, '%s: not an image/jpeg' % self.url self.jpeg = exif.JPEG(file) if 'DateTimeOriginal' in self.jpeg.exif: self.dt = exif.parse_datetime(self.jpeg.exif['DateTimeOriginal']) elif 'DateTime' in self.jpeg.exif: self.dt = exif.parse_datetime(self.jpeg.exif['DateTime']) else: self.dt = datetime.datetime(2000, 1, 1) if 'GPSVersionID' in self.jpeg.exif: lat = exif.parse_angle(self.jpeg.exif['GPSLatitude']) if self.jpeg.exif['GPSLatitudeRef'] == 'S\0': lat = -lat lon = exif.parse_angle(self.jpeg.exif['GPSLongitude']) if self.jpeg.exif['GPSLongitudeRef'] == 'W\0': lon = -lon if 'GPSAltitude' in self.jpeg.exif: gps_altitude = self.jpeg.exif['GPSAltitude'] ele = float(gps_altitude[0]) / gps_altitude[1] self.elevation_data = True else: ele = 0 self.elevation_data = False self.coord = Coord.deg(lat, lon, ele) else: self.coord = None self.elevation_data = None if 'UserComment' in self.jpeg.exif: user_comment = self.jpeg.exif['UserComment'] self.description = exif.parse_usercomment(user_comment) else: self.description = None
def trouver_deco_atterro(trace_gps, conn_bdd): '''Chercher si la base de donnees a un decollage dans un rayon de 100 m du point de depart et un atterrissage dans un rayon de 100 m du point d'arrivee de la trace GPS. Le format de la trace GPS doit etre une liste d'objets de type Coord() ''' cur = conn_bdd.cursor() dist_deco_le_plus_proche = 99999 deco_proche = None cur.execute('''SELECT * from decos order by deco''') liste_decos_bdd = cur.fetchall() # Chercher le deco le plus proche du depart de la trace GPS for deco in liste_decos_bdd: # Verifier que la latitude et la longitude sont enregistrees dans la # base de donnees try: float(deco[2]) float(deco[3]) # sinon, passer au decollage suivant except: continue coord_deco = Coord(deco[2], deco[3]) dist_deco = coord_deco.distance_to(trace_gps[0]) if dist_deco <= dist_deco_le_plus_proche : deco_proche = deco[1] dist_deco_le_plus_proche = dist_deco dist_atterro_le_plus_proche = 99999 atterro_proche = None cur.execute('''SELECT * from atterros order by atterro''') liste_atterros_bdd = cur.fetchall() # Chercher l'atterro le plus proche de l'arrive de la trace GPS for atterro in liste_atterros_bdd: # Verifier que la latitude et la longitude sont enregistrees dans la # base de donnees try: float(atterro[2]) float(atterro[3]) # sinon, passer a l'atterro suivant except: continue coord_atterro = Coord(atterro[2], atterro[3]) dist_atterro = coord_atterro.distance_to(trace_gps[-1]) if dist_atterro <= dist_atterro_le_plus_proche : atterro_proche = atterro[1] dist_atterro_le_plus_proche = dist_atterro # Verifier que le deco le plus proche est a moins de 100 m if not dist_deco_le_plus_proche < 100: deco_proche = None # Verifier que l'atterro le plus proche est a moins de 150 m if not dist_atterro_le_plus_proche < 150: atterro_proche = None return (deco_proche, atterro_proche)
def __init__(self, name, lat, lon, ele, description=None): Coord.__init__(self, lat, lon, ele) self.name = name self.description = description
def read_transcripts(path, chrom_dict): """Retrives all transcripts from the specified transcript file""" f = open(path, "r") transcripts = [] for row in txtfile.read_rows(f): if row['ID'] == "NA": tr_id = None else: tr_id = int(row['ID']) if row["NAME"] == "NA": name = None else: name = row['NAME'] # parse CDS start/end if row['CDS.START'] == 'NA': cds_start = None else: cds_start = int(row['CDS.START']) if row['CDS.END'] == 'NA': cds_end = None else: cds_end = int(row['CDS.END']) strand = int(row['STRAND']) chrom = chrom_dict[row['CHROM']] # parse exons exon_starts = [int(x) for x in row['EXON.STARTS'].split(",")] exon_ends = [int(x) for x in row['EXON.ENDS'].split(",")] if "EXON.SCORES" in row: exon_scores = [float(x) for x in row['EXON.SCORES'].split(",")] if len(exon_scores) != len(exon_starts): raise ValueError("Expected %d exon scores, got %d" % (len(exon_starts), len(exon_scores))) else: exon_scores = None if ("INTRON.SCORES" in row) and (row['INTRON.SCORES'] != 'NA'): intron_scores = [float(x) for x in row['INTRON.SCORES'].split(",")] if len(intron_scores) != len(exon_starts) - 1: raise ValueError("Expected %d intron scores, got %d" % (len(exon_starts)-1, len(intron_scores))) else: intron_scores = None if ("KNOWN.INTRON" in row) and (row['KNOWN.INTRON'] != "NA"): intron_flags = row['KNOWN.INTRON'].split(",") else: intron_flags = None exons = [] for i in range(len(exon_starts)): exon = Coord(chrom, exon_starts[i], exon_ends[i], strand) if exon_scores is not None: exon.score = exon_scores[i] exons.append(exon) tr = Transcript(name=name, exons=exons, cds_start=cds_start, cds_end=cds_end, intron_scores=intron_scores, known_intron_flags=intron_flags, idnum=tr_id) transcripts.append(tr) f.close() return transcripts