def plot_tsp_path(gps, flags, tsp_tour):
    plt.figure(figsize=(24, 12))
    m = Basemap(projection='ortho', lon_0=20.0, lat_0=20.0, resolution=None)
    m.shadedrelief()

    for (lon, lat), flag in zip(gps, flags):
        x, y = m(lon, lat)
        im = OffsetImage(flag[..., ::-1], zoom=0.8)
        ab = AnnotationBbox(im, (x, y), xycoords='data', frameon=False)
        m._check_ax().add_artist(ab)

    num_countries = len(tsp_tour)
    last_country = 0
    current_country = 0
    path_indices = [0]
    for _ in range(num_countries):
        for j in range(num_countries):
            if tsp_tour[current_country][j] and j != last_country:
                last_country = current_country
                current_country = j
                path_indices.append(current_country)
                break

    lat = [gps[i][1] for i in path_indices]
    lon = [gps[i][0] for i in path_indices]

    x, y = m(lon, lat)
    m.plot(x, y, 'o-', markersize=5, linewidth=3)

    plt.title("Country locations with TSP solution")
    plt.show()
Example #2
0
class Stereo(base.Generic):
    #_required = ['anisotropy']

    def initialize_visual(self):
        super(Stereo, self).initialize_visual()
        #self._required = RockPy.Measurements.anisotropy.Anisotropy
        # create instance of basemap with south polar projection to 90 = E
        self.stereomap = Basemap(projection='spstere', boundinglat=0, lon_0=180, resolution='l', round=True, suppress_ticks=True, rsphere=1)
        self.grid_D_spacing = 30
        self.grid_I_spacing = 15
        self.standard_features = []
        self.single_features = [self.feature_stereogrid, self.feature_stereogridlabels]
        self.add_plot()
        self.ax = self.figs[self.name][0].gca()
        self.xlabel = ''
        self.ylabel = ''

    ''' Features '''

    def feature_stereogrid(self, **plt_opt):
        # set the grid up
        Grid_D = np.arange(-180.0, 180.0, self.grid_D_spacing)
        Grid_I = np.arange(-90.0, 0.0, self.grid_I_spacing)

        # draw parallel and meridian grid, labels are off.
        self.stereomap.drawmeridians(Grid_D)
        self.stereomap.drawparallels(Grid_I, latmax=90)

    def feature_stereogridlabels(self, **plt_opt):
        # draw declination labels
        for D in np.arange(0, 360, self.grid_D_spacing):
            x = (0.55*np.sin(np.deg2rad(D)))+0.5
            y = (0.55*np.cos(np.deg2rad(D)))+0.5
            self.ax.text(x, y, "%i" % D, transform=self.ax.transAxes,
                         horizontalalignment='center', verticalalignment='center')

        # draw inclination labels
        for I in np.arange(self.grid_I_spacing, 90, self.grid_I_spacing):
            (x, y) = self.stereomap(0, -I)
            self.ax.text(x-0.1, y-0.07, "%i" % I, horizontalalignment='center', verticalalignment='center')


    def feature_points(self, m_obj, **plt_opt):
        d, i = (30, 50, 120, 150), (-10, -20, -30, -40)
        lines = self.ax.plot(*self.stereomap(d, i), **plt_opt)
        self._add_line_text_dict(m_obj.sample_obj.name, '_'.join(m_obj.stypes), '_'.join(map(str, m_obj.svals)), lines)


    def show(self):
        self.stereomap._check_ax().set_xlim((0.5, -4.5))  # reduce size of plot to make space for labels
        self.stereomap._check_ax().set_ylim((0.5, -4.5))  # reduce size of plot to make space for labels
        super(Stereo, self).show()
Example #3
0
    def generate_map(self, lat, lon):
        lat = float(lat)
        lon = float(lon)
        icon = join(dirname(__file__), self.settings["iss_icon"])
        output = join(tempfile.gettempdir(), "iss.jpg")
        lat_0 = None
        lon_0 = None
        if self.settings["center_iss"]:
            lat_0 = lat
            lon_0 = lon
        elif self.settings["center_location"]:
            lat_0 = self.location["coordinate"]["latitude"]
            lon_0 = self.location["coordinate"]["longitude"]
        if self.settings["map_style"] == "cyl":
            lat_0 = None
            lon_0 = None
        m = Basemap(projection=self.settings["map_style"],
                    resolution=None,
                    lat_0=lat_0,
                    lon_0=lon_0)
        m.bluemarble()
        x, y = m(lon, lat)

        iss = plt.imread(icon)
        im = OffsetImage(iss, zoom=self.settings["iss_size"])
        ab = AnnotationBbox(im, (x, y), xycoords='data', frameon=False)

        # Get the axes object from the basemap and add the AnnotationBbox artist
        m._check_ax().add_artist(ab)

        plt.savefig(output,
                    dpi=self.settings["dpi"],
                    bbox_inches='tight',
                    facecolor="black")
        plt.close()
        return output
# text = plt.text(0, 0, 'International\n Space Station', fontweight='bold',
#                 color=(0, 0.2, 1))
# iss_point, = plt.plot([], [], 'ob', markersize=10)

iss_image = Image.open('icon/iss_new.png')
# process_image(iss_image, (12, 12, 36))
# iss_image.save('icon/iss_new.png')

imagebox = OffsetImage(iss_image, zoom=0.08)
iss_icon = AnnotationBbox(imagebox,
                          map(0, 0),
                          xybox=(0, -4),
                          xycoords='data',
                          boxcoords='offset points',
                          frameon=False)
map._check_ax().add_artist(iss_icon)


def get_coords(time):
    iss_pos.compute(time)
    lon = degrees(iss_pos.sublong)
    lat = degrees(iss_pos.sublat)
    return lon, lat


def show_route():
    lon_list = []
    lat_list = []
    # ISS route from the past
    for seconds in range(-1000, 1, 10):
        lon, lat = get_coords(datetime.utcnow() + timedelta(seconds=seconds))
Example #5
0
class BaseMap():
    def __init__(self):

        '''
        self.fig = plt.figure(figsize=(10,10))
        self.map = Basemap(
                urcrnrlat=71.8,
                urcrnrlon=37.7,
                llcrnrlat=48.,
                llcrnrlon=3.08,
                    #resolution='h', 
                    resolution='l',
                    area_thresh=5000,
                    projection='cass', lat_0 = 50., lon_0 = 30.
                    )
        '''
        self.fig = plt.figure(figsize=(10,20))


        ax = self.fig.add_axes([0, 0, 1, 1])
        ax.axis('off')

        self.map = Basemap(
                #49.267693, 8.406459 # medersche
                #50.166281, 8.659168 # frankfurt mellsig
                urcrnrlat = 51.7,
                urcrnrlon = 10.1,
                llcrnrlat = 48.3,
                llcrnrlon = 6.1,
                    #resolution='h', 
                    resolution='c',
                    area_thresh=5000,
                    projection='cass', lat_0 = 50., lon_0 = 8.65
                    )

        #'''

        self.map.etopo()
        self.map.drawcountries(color='k', linewidth=1)
        self.map.drawcoastlines(color='k', linewidth=1)

    def show_coords(self, coords):
        lat,lon = coords[0], coords[1]
        print "Plotting for coordinates lat: ",lat," ,lon: ",lon
        x,y = self.map(lon, lat)
        self.map.plot(x, y, 'bo', markersize=10)

        benz = np.array(Image.open('jaguar.png'))
        im = OffsetImage(benz, zoom=1)
        ab = AnnotationBbox(im, (x,y), xycoords='data', frameon=False)

        # Get the axes object from the basemap and add the AnnotationBbox artist
        self.map._check_ax().add_artist(ab)
        plt.show()

    def get_angle(self, x1, y1, x2, y2):
        dx = x2 - x1
        dy = y2 - y1
        rads = atan2(-dy,dx)
        rads %= 2*pi
        degs = degrees(rads)
        return degs


    def rotateAndScale(self, img, scaleFactor = 0.5, degreesCCW = 30):
        (oldY,oldX) = img.shape[0:2] #note: numpy uses (y,x) convention but most OpenCV functions use (x,y)
        M = cv2.getRotationMatrix2D(center=(oldX/2,oldY/2), angle=degreesCCW, scale=scaleFactor) #rotate about center of image.

        #choose a new image size.
        newX,newY = oldX*scaleFactor,oldY*scaleFactor
        #include this if you want to prevent corners being cut off
        r = np.deg2rad(degreesCCW)
        newX,newY = (abs(np.sin(r)*newY) + abs(np.cos(r)*newX),abs(np.sin(r)*newX) + abs(np.cos(r)*newY))

        #So I will find the translation that moves the result to the center of that region.
        (tx,ty) = ((newX-oldX)/2,(newY-oldY)/2)
        M[0,2] += tx #third column of matrix holds translation, which takes effect after rotation.
        M[1,2] += ty

        rotatedImg = cv2.warpAffine(img, M, dsize=(int(newX),int(newY)))
        return rotatedImg

    def show_coord_train(self, coords, cnt=0):
        thismap = self.map
        #thismap = pickle.load(open('map.pickle','rb'))

        for i in range(0,len(coords)-1):
            lat,lon = coords[i][0], coords[i][1]
            lat1,lon1 = coords[i+1][0], coords[i+1][1]

            #print "Plotting for coordinates lat: ",lat," ,lon: ",lon
            x,y = thismap(lon, lat)
            x1,y1 = thismap(lon1, lat1)
            thismap.plot(x, y, 'bo', markersize=10)
            thismap.plot((x,x1),(y,y1), 'b-')

        x_o, y_o = 0,0 
        try:
            lat_o, lon_o = coords[-2][0], coords[-2][1]
            x_o, y_o = thismap(lon_o, lat_o)
        except Exception as e:
            print e
            pass

        lat,lon = coords[-1][0], coords[-1][1]
        x,y = thismap(lon, lat)

        thismap.plot(x, y, 'bo', markersize=10)

        # rotate car icon acoording to last two coordinates
        benz = cv2.imread("jaguar.png", -1)

        try:
            ang = 180 - self.get_angle(x,y,x_o,y_o)
            dst = self.rotateAndScale(benz, 1., ang)
        except Exception as e:
            print "Rotate: ", e
            dst = benz
            pass

        # only plot the benz for the last coord 
        # if you want to rotate by 90, use np.rot90(benz)
        im = OffsetImage(dst, zoom=1.)
        try:
            self.ab.remove()
            del self.ab
        except Exception as e:
            print e
            pass
        self.ab = AnnotationBbox(im, (x,y), xycoords='data', frameon=False)

        # Get the axes object from the basemap and add the AnnotationBbox artist
        thismap._check_ax().add_artist(self.ab)
        with open('./tmp_files/map_image_%08d.png' % cnt, 'w') as outfile:
            self.fig.canvas.print_png(outfile)
Example #6
0
class Stereo(base.Generic):
    #_required = ['anisotropy']

    def initialize_visual(self):
        super(Stereo, self).initialize_visual()
        #self._required = RockPy.Measurements.anisotropy.Anisotropy
        # create instance of basemap with south polar projection to 90 = E
        self.stereomap = Basemap(projection='spstere',
                                 boundinglat=0,
                                 lon_0=180,
                                 resolution='l',
                                 round=True,
                                 suppress_ticks=True,
                                 rsphere=1)
        self.grid_D_spacing = 30
        self.grid_I_spacing = 15
        self.standard_features = []
        self.single_features = [
            self.feature_stereogrid, self.feature_stereogridlabels
        ]
        self.add_plot()
        self.ax = self.figs[self.name][0].gca()
        self.xlabel = ''
        self.ylabel = ''

    ''' Features '''

    def feature_stereogrid(self, **plt_opt):
        # set the grid up
        Grid_D = np.arange(-180.0, 180.0, self.grid_D_spacing)
        Grid_I = np.arange(-90.0, 0.0, self.grid_I_spacing)

        # draw parallel and meridian grid, labels are off.
        self.stereomap.drawmeridians(Grid_D)
        self.stereomap.drawparallels(Grid_I, latmax=90)

    def feature_stereogridlabels(self, **plt_opt):
        # draw declination labels
        for D in np.arange(0, 360, self.grid_D_spacing):
            x = (0.55 * np.sin(np.deg2rad(D))) + 0.5
            y = (0.55 * np.cos(np.deg2rad(D))) + 0.5
            self.ax.text(x,
                         y,
                         "%i" % D,
                         transform=self.ax.transAxes,
                         horizontalalignment='center',
                         verticalalignment='center')

        # draw inclination labels
        for I in np.arange(self.grid_I_spacing, 90, self.grid_I_spacing):
            (x, y) = self.stereomap(0, -I)
            self.ax.text(x - 0.1,
                         y - 0.07,
                         "%i" % I,
                         horizontalalignment='center',
                         verticalalignment='center')

    def feature_points(self, m_obj, **plt_opt):
        d, i = (30, 50, 120, 150), (-10, -20, -30, -40)
        lines = self.ax.plot(*self.stereomap(d, i), **plt_opt)
        self._add_line_text_dict(m_obj.sample_obj.name, '_'.join(m_obj.stypes),
                                 '_'.join(map(str, m_obj.svals)), lines)

    def show(self):
        self.stereomap._check_ax().set_xlim(
            (0.5, -4.5))  # reduce size of plot to make space for labels
        self.stereomap._check_ax().set_ylim(
            (0.5, -4.5))  # reduce size of plot to make space for labels
        super(Stereo, self).show()
            'magnemite', 'magneton', "farfetch'd", 'doduo', 'dodrio', 'seel',
            'grimer', 'muk', 'shellder', 'cloyster', 'gastly', 'haunter',
            'gengar', 'onix', 'drowzee', 'hypno', 'krabby', 'kingler',
            'voltorb', 'electrode', 'exeggcute', 'exeggutor', 'cubone',
            'marowak', 'hitmonlee', 'hitmonchan', 'lickitung', 'koffing',
            'weezing', 'rhyhorn', 'rhydon', 'chansey', 'tangela', 'kangaskhan',
            'horsea', 'seadra', 'goldeen', 'seaking', 'staryu', 'starmie',
            'mr. mime', 'scyther', 'jynx', 'electabuzz', 'magmar', 'pinsir',
            'tauros', 'magikarp', 'gyarados', 'lapras', 'ditto', 'eevee', 
            'vaporeon', 'jolteon', 'flareon', 'porygon', 'omanyte', 'omastar',
            'kabuto', 'kabutops', 'aerodactyl', 'snorlax', 'articuno', 'zapdos',
            'moltres', 'dratini', 'dragonair', 'dragonite', 'mewtwo', 'mew']

state_loc_list = [(k, v[0], v[1], state_sum_dict[k], top_pokemon_by_loc(k, state_len_dict, 1, e_p)[0][0]) for k, v in state_loc_dict.iteritems()]
state_loc_zip = zip(*state_loc_list)
state_names = state_loc_zip[0]
state_longs = state_loc_zip[1]
state_lats = state_loc_zip[2]
state_sums = state_loc_zip[3]
state_pokemons = state_loc_zip[4]

for lon, lat, n_sum, pokemon in zip(state_longs, state_lats, state_sums, state_pokemons):
	if n_sum > 0 and pokemon != None:
		x, y = my_map(lon, lat)
		ab = place_poke_img(x, y, pokemon)
		my_map._check_ax().add_artist(ab)

plt.title('Most popular starter pokemon for continental U.S. states')

#plt.show()
plt.savefig('starters_by_state.png', dpi=300, frameon=False, format="png", facecolor='white')
Example #8
0
lat_j = str(jingdu[u'纬度']).split()[1]
lat_j = re.findall(r'(\w*[0-9]+)\w*', lat_j)  #get the number
lat_j = float(lat_j[0])

lon_j = str(jingdu[u'经度']).split()[1]
lon_j = re.findall(r'(\w*[0-9]+)\w*', lon_j)  #get the number
lon_j = float(lon_j[0] + '.' + lon_j[1])

img = plt.imread('2.png', format='jpeg')

cv2.destroyAllWindows()

m = Basemap(projection='mill',
            llcrnrlon=-180,
            llcrnrlat=-55,
            urcrnrlon=180,
            urcrnrlat=85)

m.drawcoastlines()
m.fillcontinents()
m.drawcountries()
m.drawgreatcircle(lon_s, lat_s, lon_j, lat_j, linewidth=2, color='b')

x, y = m(lon_s, lat_s)
im = OffsetImage(img, zoom=0.3)
ab = AnnotationBbox(im, (x, y), xycoords='data', frameon=False)

m._check_ax().add_artist(ab)

plt.show()