示例#1
0
    def can_move_piece(self, pos1, pos2, player_turn, should_promote=False):
        ''' Return True if move is valid.
            Verifies:
            - Correct player's turn,
            - Promotion is valid (especailly for pawns)
            - Piece is on last row to be promoted
        '''
        pz = self.get_piece_at_pos(pos1)
        if pz is not '__' and pz.can_move(self.board, pos2):
            if not self.verify_player_turn(pz, player_turn):
                return False

            if isinstance(pz, King) and self.pos_in_check(pos2, player_turn):
                return False

            if should_promote or self.should_promote_pawn(
                    pz, player_turn, pos2):
                if pz.promoted or isinstance(pz, King) or isinstance(
                        pz, GoldGeneral):
                    return False

                if not((player_turn == 'UPPER' and utils.get_coords(pos2)[1] == 0) or \
                    (player_turn == 'lower' and utils.get_coords(pos2)[1] == const.BOARD_SIZE - 1) or \
                    (player_turn == 'UPPER' and utils.get_coords(pos1)[1] == 0) or \
                    (player_turn == 'lower' and utils.get_coords(pos1)[1] == const.BOARD_SIZE - 1)):
                    return False

            pz2 = self.get_piece_at_pos(pos2)
            if pz2 is not '__' and pz2.team == pz.team:
                return False

            return True

        return False
示例#2
0
    def visualize(self, filename="network"):
        dist = 20
        total_items = len(self.network)
        items = self.network.items()
        delta = 2 * math.pi / total_items

        temp = {}
        i = 0
        for node, _ in items:
            temp[node] = i
            i = i + 1
        i = 0
        drawn = []
        for node, connectors in items:
            print(node)
            x, y = get_coords(i, delta)
            for connector in connectors:
                if not (temp[connector] in drawn):
                    xc, yc = get_coords(temp[connector], delta)
                    plt.plot([x, xc], [y, yc], zorder=1)
            circ = plt.Circle((x, y), 1.5, color='black', zorder=2)
            plt.gca().add_patch(circ)
            plt.text(x - 0.5, y - 0.5, node, color='w', zorder=3)
            drawn.append(node)
            i = i + 1
        plt.savefig(filename)
        return self
示例#3
0
def visualize_n(ax, network, filename="network", special_edge=()):
    dist = 20
    total_items = len(network)
    items = network.items()
    delta = 2 * math.pi / total_items

    temp = {}
    i = 0
    for node, _ in items:
        temp[node] = i
        i = i + 1
    i = 0
    drawn = []
    ax.axis('off')
    ax.set_box_aspect(1)
    special_edge_off = False
    # if (special_edge):
    #     network[special_edge[0]].append(special_edge[1])
    #     special_edge_off = True
    for node, connectors in items:
        x, y = get_coords(i, delta)
        for connector in connectors:
            spec = False
            if special_edge:
                if ((node == special_edge[0]) and
                    (connector == special_edge[1])) or (
                        (node == special_edge[1]) and
                        (connector == special_edge[0])):
                    spec = True
            if not (temp[connector] in drawn):
                xc, yc = get_coords(temp[connector], delta)
                if spec:
                    if special_edge_off:
                        ax.plot([x, xc], [y, yc],
                                zorder=1,
                                linewidth=4,
                                dash_capstyle='round',
                                color="#FFC0CB")
                    else:
                        ax.plot([x, xc], [y, yc],
                                zorder=1,
                                linewidth=4,
                                dash_capstyle='round')
                else:
                    ax.plot([x, xc], [y, yc], linewidth=1, zorder=1)
        i = i + 1
    i = 0
    for node, connectors in items:
        x, y = get_coords(i, delta)
        circ = plt.Circle((x, y), 1.5, color='black', zorder=2)
        ax.add_patch(circ)
        ax.text(x - 0.5, y - 0.5, node, color='w', zorder=3)
        i = i + 1
示例#4
0
def main() -> None:

    # API params
    with open("config.yaml", "r", encoding="utf-8") as f:
        params_API = yaml.safe_load(f)

    # data
    flights = get_flights()
    stations = get_stations()

    # setup
    train_duration = getDuration(**params_API)
    logging.basicConfig(filename="data/geocode.log", level=logging.INFO)

    links = []
    for flight in tqdm(flights.itertuples(), total=flights.shape[0]):

        # geocode departure/arrival
        try:
            lat_d, lon_d = get_coords(flight.departure)
            lat_a, lon_a = get_coords(flight.arrival)
        except TypeError:
            logging.warning("Geocode error : %s-%s}", flight.departure,
                            flight.arrival)
            continue

        # keep only metro flight
        if not in_metro(lat_d, lon_d) or not in_metro(lat_a, lon_a):
            continue

        # compute train duration
        departure_station = stations[flight.departure]
        arrival_station = stations[flight.arrival]
        duration = train_duration.compute(departure_station, arrival_station)

        links.append({
            "departure": flight.departure,
            "arrival": flight.arrival,
            "lat_d": lat_d,
            "lon_d": lon_d,
            "lat_a": lat_a,
            "lon_a": lon_a,
            "duration": duration,
        })

    links_df = pd.DataFrame(links)
    links_df = links_df.merge(flights, on=["departure", "arrival"])
    links_df.to_csv("data/links.csv")
示例#5
0
    def get_possible_moves(board, position, team, promoted, supported = True, enhance_piece = None):
        possible_moves = set()
        if enhance_piece is not None:
            possible_moves |= enhance_piece.get_possible_moves(board, position, team, suporting_piece.promoted, False)
        if supported:
            suporting_piece = Piece.get_supporting_piece(board, position, team)
            if suporting_piece != '__':
                possible_moves |= suporting_piece.get_possible_moves(board, position, team, suporting_piece.promoted, False)
        if promoted:
            possible_moves |= GoldGeneral.get_possible_moves(board, position, team, False, False)
            return possible_moves

        x, y = utils.get_coords(position)

        for i in range(-1, 2):
            for j in range(-1, 2):
                new_pos = utils.get_a1(x + i, y + j)
                if team == 'UPPER':
                    new_pos = utils.get_a1(x + i, y - j)

                if utils.in_bounds(new_pos) and not (i == 0 and j == 0) \
                    and not (i == -1 and j == 0) and not (i == 1 and j == 0) \
                    and not (i == 0 and j == -1):
                    possible_moves.add(new_pos)
        return possible_moves
示例#6
0
    def get_buoy_coords(self, direction, curr_x, curr_y):
        """get_buoy_coords(distance, x_displacement, direction, curr_x, curr_y) returns the
        x and y coordinates of a buoy detected by a buoy detector.

        Return:
            list: x, y coordinates representing the center of the front projection of another buoy.
        """
        dist, x_offset = find_distance_largest_contour(self)
        return get_coords([dist], [x_offset], direction, curr_x, curr_y)[0]
示例#7
0
 def set_coord(self, piece, a1=None):
     ''' Sets coordinate of a piece. If a1 is None, defaults to piece.position. '''
     if a1 is None:
         a1 = piece.position
     if utils.in_bounds(a1):
         x, y = utils.get_coords(a1)
         self.board[x][y] = piece
     else:
         print("Error setting coordinate.")
示例#8
0
    def get_possible_moves(board, position, team, promoted, supported = True, enhance_piece = None):
        possible_moves = set()
        if enhance_piece is not None:
            possible_moves |= enhance_piece.get_possible_moves(board, position, team, suporting_piece.promoted, False)
        if supported:
            suporting_piece = Piece.get_supporting_piece(board, position, team)
            if suporting_piece != '__':
                possible_moves |= suporting_piece.get_possible_moves(board, position, team, suporting_piece.promoted, False)
        if promoted:
            possible_moves |= King.get_possible_moves(board, position, team, False, False)
        x, y = utils.get_coords(position)

        for i in range(1, len(board)):
            new_pos = utils.get_a1(x + i, y + i)
            if utils.in_bounds(new_pos):
                pz = board[x+i][y+i]
                if pz != '__':
                    if pz.team != team:
                        possible_moves.add(new_pos)
                    break
                else:
                    possible_moves.add(new_pos)

        for i in range(1, len(board)):
            new_pos = utils.get_a1(x - i, y + i)
            if utils.in_bounds(new_pos):
                pz = board[x-i][y+i]
                if pz != '__':
                    if pz.team != team:
                        possible_moves.add(new_pos)
                    break
                else:
                    possible_moves.add(new_pos)
        for i in range(1, len(board)):
            new_pos = utils.get_a1(x + i, y - i)
            if utils.in_bounds(new_pos):
                pz = board[x+i][y-i]
                if pz != '__':
                    if pz.team != team:
                        possible_moves.add(new_pos)
                    break
                else:
                    possible_moves.add(new_pos)
        for i in range(1, len(board)):
            new_pos = utils.get_a1(x - i, y - i)
            if utils.in_bounds(new_pos):
                pz = board[x-i][y-i]
                if pz != '__':
                    if pz.team != team:
                        possible_moves.add(new_pos)
                    break
                else:
                    possible_moves.add(new_pos)
        return possible_moves
示例#9
0
 def get_supporting_piece(board, position, team):
     x, y = utils.get_coords(position)
     if team == 'lower':
         if utils.in_bounds(utils.get_a1(x, y-1)):
             if board[x][y-1] != '__' and board[x][y-1].team == team:
                 return board[x][y-1]
     else:
         if utils.in_bounds(utils.get_a1(x, y+1)):
             if board[x][y+1] != '__' and board[x][y+1].team == team:
                 return board[x][y+1]
     return '__'
示例#10
0
 def get_piece_at_pos(self, a1):
     ''' Returns piece object at an a1 location. '''
     if utils.in_bounds(a1):
         x, y = utils.get_coords(a1)
         if isinstance(self.board[x][y], Piece):
             return self.board[x][y]
         else:
             return '__'
     else:
         print("Coordinate not in bounds.")
         return False
示例#11
0
def visualize(network, filename="network", special_edge=()):
    dist = 20
    total_items = len(network)
    items = network.items()
    delta = 2 * math.pi / total_items

    temp = {}
    i = 0
    for node, _ in items:
        temp[node] = i
        i = i + 1
    i = 0
    drawn = []
    plt.cla()
    plt.axis('off')
    for node, connectors in items:
        x, y = get_coords(i, delta)
        for connector in connectors:
            spec = False
            if len(special_edge) > 0:
                if ((node == special_edge[0]) and
                    (connector == special_edge[1])) or (
                        (node == special_edge[1]) and
                        (connector == special_edge[0])):
                    spec = True
            if not (temp[connector] in drawn):
                xc, yc = get_coords(temp[connector], delta)
                if spec:
                    plt.plot([x, xc], [y, yc],
                             zorder=1,
                             linewidth=4,
                             dash_capstyle='round')
                else:
                    plt.plot([x, xc], [y, yc], linewidth=1, zorder=1)
        circ = plt.Circle((x, y), 1.5, color='black', zorder=2)
        plt.gca().add_patch(circ)
        plt.text(x - 0.5, y - 0.5, node, color='w', zorder=3)
        drawn.append(node)
        i = i + 1
    plt.savefig(filename)
示例#12
0
    def can_drop_piece(self, player_turn, piece, pos):
        ''' Return True if drop is possible. '''
        piece_name = str(piece)
        if len(piece_name) > 1:
            piece_name = piece_name[1]

        # Cannot place Pawn in promotion zone or in same row as another Pawn.
        if piece_name.lower() == 'p':
            if ((player_turn == 'UPPER' and utils.get_coords(pos)[1] == 0) or \
                (player_turn == 'lower' and utils.get_coords(pos)[1] == const.BOARD_SIZE - 1)):
                return False

            x, y = utils.get_coords(pos)
            for j in range(const.BOARD_SIZE):
                if isinstance(self.board[x][j],
                              Pawn) and self.board[x][j].team == player_turn:
                    return False

            board_obj = deepcopy(self)
            board_obj.drop_piece(player_turn, piece_name, pos)
            other_player = utils.get_other_player(player_turn)
            if board_obj.king_in_check(
                    other_player) and not find_available_moves(
                        board_obj, other_player):
                return False

        # Only drop pieces in empty spaces
        if self.get_piece_at_pos(pos) == '__' or self.get_piece_at_pos(
                pos).team == player_turn:
            if player_turn == 'UPPER':
                for i in range(len(self.upper_captures)):
                    if self.upper_captures[i].lower() == piece_name.lower():
                        return True

            elif player_turn == 'lower':
                for i in range(len(self.lower_captures)):
                    if self.lower_captures[i] == piece_name:
                        return True
        return False
示例#13
0
	def post(self):
		title=self.request.get("title")
		art=self.request.get("art")
		if title and art:
			coords = utils.get_coords(self.request.remote_addr)
			a = Art(title= title, art = art)
			if coords:
				a.coords = coords
			a.put()
			self.redirect("/")
		else:
			error = "we need both a title and some artwork!"
			self.render_front(title,art, error=error)
示例#14
0
def me_loss_func(reference, imgs, flows):
    b, c, h, w = reference.size()
    lambda1 = 0.01
    coords = get_coords(h, w)
    mappings = [coords + i for i in flows]
    warped = [backward_warp(reference, mappings[i]) for i in range(len(flows))]
    multi_reference = torch.stack([reference] * len(imgs), axis=0)
    tensor_imgs = torch.Tensor(imgs)
    warp_loss = torch.sum(torch.abs(tensor_imgs - multi_reference))

    multi_flows = torch.stack(flows, dim=0)
    flow_loss = torch.sum(torch.abs(multi_flows))

    return warp_loss + lambda1 * flow_loss
示例#15
0
	def post(self):
		title = self.request.get("subject")
		blog = self.request.get("content")
		if title and blog:
			coords = utils.get_coords(self.request.remote_addr)
			newBlog = BlogPost(title=title, blog=blog, coords=coords)
			newBlog.put()
			FrontPage(update=True)
			val = newBlog.key().id()
			PermaLinkPage(update=newBlog)
			self.redirect("/blog/"+str(val))
		else:
			error = "You need a title and blog entry!"
			self.render_blog(error=error,title=title)
示例#16
0
文件: aschii.py 项目: sub14305k/bs_hw
    def post(self):
        title = self.request.get("title")
        art = self.request.get("art")

        if art and title:
            a = Art(title = title, art = art)
            coords = utils.get_coords(self.request.remote_addr)
            if coords:
                a.coords = coords

            a.put()
            utils.top_arts(True)

            self.redirect("/course_work/unit3/ASCIIChan")
        else:
            error = "We need both title and some artwork!"
            self.render_ASCII_page(title,art,error) 
示例#17
0
    def post(self):
        title = self.request.get("title")
        art = self.request.get("art")

        if title and art:
            p = Art(parent=art_key, title = title, art = art)
            #lookup the user's coordinates from their IP
            coords = get_coords(self.request.remote_addr)
            #if we have coordinates, add them to the art
            if coords:
                p.coords = coords

            p.put()

            self.redirect("/ascii")
        else:
            error = "we need both a title and some artwork!"
            self.render_front(error = error, title = title, art =art)
示例#18
0
    def post(self):
        title = self.request.get('title')
        art = self.request.get('art')

        if title and art:
            p = Art(title = title, art = art)
            coords = get_coords(self.request.remote_addr) # lookup the user's coordinates from their IP
            if coords:
                p.author_loc = coords # if we have coordinates, add them to Art
            
            p.put()
            # rerun the query and update the cache
            top_arts(True)

            self.redirect('/ascii')
        else:
            error = "we need both a title and some artwork!"
            self.render_ascii(title, art, error)
示例#19
0
    def get_possible_moves(board, position, team, promoted, supported = True, enhance_piece = None):
        possible_moves = set()
        if enhance_piece is not None:
            possible_moves |= enhance_piece.get_possible_moves(board, position, team, suporting_piece.promoted, False)
        if supported:
            suporting_piece = Piece.get_supporting_piece(board, position, team)
            if suporting_piece != '__':
                possible_moves |= suporting_piece.get_possible_moves(board, position, team, suporting_piece.promoted, False)

        if promoted:
            possible_moves += GoldGeneral.get_possible_moves(board, position, team, False, False)
            print(possible_moves)

            return possible_moves

        x, y = utils.get_coords(position)

        new_pos = utils.get_a1(x, y + 1)
        if team == 'UPPER':
            new_pos = utils.get_a1(x, y - 1)
        if utils.in_bounds(new_pos):
            possible_moves.add(new_pos)
        print(possible_moves)
        return possible_moves
示例#20
0
 def forward(self, img, flow, scale):
     mapping = (get_coords(img) + flow) * scale  # (b, 2, h, w)
     res = forward_warp(img, mapping)  # (b, 1, h*scale, w*scale)
     return res
示例#21
0
 def should_promote_pawn(self, pz, player_turn, pos2):
     return isinstance(pz, Pawn) and ((player_turn == 'UPPER' and utils.get_coords(pos2)[1] == 0) or \
             (player_turn == 'lower' and utils.get_coords(pos2)[1] == const.BOARD_SIZE - 1))
示例#22
0
import matplotlib.pyplot as plt
import datetime
import utils
from matplotlib.colors import from_levels_and_colors
import os
import seaborn as sns
import pandas as pd

home_folder = os.getenv('HOME_FOLDER')

datetime_now = datetime.datetime.utcnow()

time, snow = utils.get_snow_data(datetime_now)
# Snow is shape (6, 909, 671), previous 6 hours

lons, lats = utils.get_coords()

fig = plt.figure(figsize=(11, 11))

m = Basemap(projection='cyl', llcrnrlon=lons.min(), llcrnrlat=lats.min(),\
              urcrnrlon=lons.max(), urcrnrlat=lats.max(),  resolution='i')
x, y = m(lons, lats)

levels_snow = (0.5, 1, 2.5, 5, 10, 15, 20, 25, 30, 40, 50, 70, 90, 150, 200)

colors_tuple = pd.read_csv(home_folder + '/cmap_snow_wxcharts.rgba',
                           header=None).values
cmap_snow, norm_snow = from_levels_and_colors(levels_snow,
                                              sns.color_palette(
                                                  colors_tuple,
                                                  n_colors=len(levels_snow)),