Beispiel #1
0
    def do_plot(self, dataset):
        #for dataset in r533:
        points, plot_type, lons, lats, num_pts_lon, num_pts_lat, params = dataset
        plot_dt, plot_title, freq, idx = params
        #plt.figure(figsize=(12,6))
        m = Basemap(projection='cyl', resolution='l')
        m.drawcoastlines(color='black', linewidth=0.75)
        m.drawcountries(color='grey')
        m.drawmapboundary(color='black', linewidth=1.0)
        m.drawmeridians(np.arange(0,360,30))
        m.drawparallels(np.arange(-90,90,30))

        X,Y = np.meshgrid(lons, lats)

        #todo remove hard-coded values for vmin and vmax
        #im = m.pcolormesh(X, Y, points, shading='gouraud', cmap=plt.cm.jet, latlon=True, vmin=-20, vmax=40)
        #im = m.pcolormesh(X, Y, points, shading='gouraud', cmap=plt.cm.jet, latlon=True, vmin=-20, vmax=40)
        im = m.imshow(points, interpolation='bilinear', vmin=0, vmax=100)

        if self.plot_terminator:
            m.nightshade(plot_dt)

        cb = m.colorbar(im,"bottom", size="5%", pad="2%")
        plt.title(plot_title)

        plot_fn = "area_{:s}_{:s}_{:s}.png".format(plot_type, plot_dt.strftime("%H%M_%b_%Y"), "d".join(str(freq).split('.')))
        print ("Saving file ", plot_fn)
        plt.savefig(plot_fn, dpi=float(self.dpi), bbox_inches='tight')
Beispiel #2
0
    def polar_quiver_wind(self, ax, ns='N'):
        # Wind vector in lat-long coordinates.
        # For different map projections, the arithmetics to calculate xywind
        # are different
        if self.empty:
            return
        from mpl_toolkits.basemap import Basemap
        from apexpy import Apex
        # Creat polar coordinates
        projection,fc = ('npstere',1) if ns=='N' else ('spstere',-1)
        m = Basemap(projection=projection,boundinglat=fc*40,lon_0=0,resolution='l')
        m.drawcoastlines(color='gray',zorder=1)
        m.fillcontinents(color='lightgray',zorder=0)
        dt = self.index.min() + (self.index.max()-self.index.min())/2
        m.nightshade(dt,zorder=2)
        #m.drawparallels(np.arange(-80,81,20))
        #m.drawmeridians(np.arange(-180,181,60),labels=[1,1,1,1])

        # Calculate mlat and mlon
        lat_grid = np.arange(-90,91,10)
        lon_grid = np.arange(-180,181,10)
        lon_grid, lat_grid = np.meshgrid(lon_grid, lat_grid)
        gm = Apex(date=2005)
        mlat,mlon = gm.convert(lat_grid,lon_grid,'geo','apex')
        hc1 = m.contour(lon_grid,lat_grid,mlat,levels=np.arange(-90,91,10),
                        colors='k', zorder=3, linestyles='dashed',
                        linewidths=1, latlon=True)
        # hc2 = m.contour(lon_grid,lat_grid,mlon,levels=np.arange(-180,181,45),
        #                 colors='k', zorder=3, linestyles='dashed', latlon=True)
        plt.clabel(hc1,inline=True,colors='k',fmt='%d')
        # plt.clabel(hc2,inline=True,colors='k',fmt='%d')

        # Calculate and plot x and y winds
        lat = self.lat
        lon = self.long
        wind = self.wind
        winde1 = self.winde
        winde = winde1*wind
        windn1 = self.windn
        windn = windn1*wind
        # only appropriate for the npstere and spstere
        xwind = fc*winde*np.cos(lon/180*np.pi)-windn*np.sin(lon/180*np.pi)
        ywind = winde*np.sin(lon/180*np.pi)+fc*windn*np.cos(lon/180*np.pi)
        hq = m.quiver(np.array(lon),np.array(lat),xwind,ywind,color='blue',
                      scale=300, scale_units='inches',zorder=3, latlon=True)
        #plt.quiverkey(hq,1.05,1.05,100,'100 m/s',coordinates='axes',labelpos='E')
        #m.scatter(np.array(lon),np.array(lat),
        #          s=50, c=self.index.to_julian_date(),linewidths=0, zorder=4,latlon=True)
        return m
Beispiel #3
0
def plotBase(fig, dt=None):
    m = Basemap(projection='merc',
                lon_0=0,lat_0=0,lat_ts=0,
                llcrnrlat=0,urcrnrlat=50,
                llcrnrlon=-100,urcrnrlon=-50,
                resolution='l')
    m.drawcountries(linewidth=1, color='k')
    m.drawmapscale(-90, 5, -90, 5, 1000, barstyle='fancy')
    m.bluemarble(scale=1)

    # Get Position of NYC, longitude -74.0064, latitude 40.7142
    x,y    = m(-74.0064, 40.7142)
    # Plot NYC
    m.scatter(x, y, s=100,  marker='*', color='0.5', alpha=1)
    plt.text(x,y,'NYC', fontsize='15')

    if dt is not None: m.nightshade(dt, alpha = 0.3)
    return m
Beispiel #4
0
def geramapa(idx):
    lon = stars[idx].ra - datas[idx].sidereal_time('mean', 'greenwich')

    m = Basemap(projection='ortho',lat_0=stars[idx].dec.value,lon_0=lon.value,resolution='l')
# draw coastlines, country boundaries, fill continents.
    m.shadedrelief()
    m.drawcoastlines(linewidth=0.25)
    m.drawcountries(linewidth=0.4)
    m.drawstates(linewidth=0.4)
#m.fillcontinents(color='coral',lake_color='aqua')
# draw the edge of the map projection region (the projection limb)
#m.drawmapboundary(fill_color='aqua')
# draw lat/lon grid lines every 30 degrees.
    m.drawmeridians(np.arange(0,360,30))
    m.drawparallels(np.arange(-90,90,30))
    if os.path.isfile(sitearq) == True:
        xpt,ypt = m(sites['lon'],sites['lat'])
        m.plot(xpt,ypt,'bo')
    CS=m.nightshade(datas[idx].datetime, alpha=0.2)
    a, b =m(lon.value, stars[idx].dec.value)
    a = a*u.m
    b = b*u.m
    dista = (dist[idx].to(u.km)*ca[idx].to(u.rad)).value*u.km
    disterr = (dist[idx].to(u.km)*erro.to(u.rad)).value*u.km
    ax = a + dista*np.sin(pa[idx])
    ax2 = ax + 1000*u.km*vec*np.cos(pa[idx])
    ax3 = ax2 - tamanho/2*np.sin(pa[idx])
    ax4 = ax2 + tamanho/2*np.sin(pa[idx])
    ax5 = a + (dista-disterr)*np.sin(pa[idx]) + 1000*u.km*vec*np.cos(pa[idx])
    ax6 = a + (dista+disterr)*np.sin(pa[idx]) + 1000*u.km*vec*np.cos(pa[idx])
    by = b + dista*np.cos(pa[idx])
    by2 = by - 1000*u.km*vec*np.sin(pa[idx])
    by3 = by2 - tamanho/2*np.cos(pa[idx])
    by4 = by2 + tamanho/2*np.cos(pa[idx])
    by5 = b + (dista-disterr)*np.cos(pa[idx]) - 1000*u.km*vec*np.sin(pa[idx])
    by6 = b + (dista+disterr)*np.cos(pa[idx]) - 1000*u.km*vec*np.sin(pa[idx])
    m.plot(ax,by, 'ro', markersize=20)
    m.plot(ax2.to(u.m),by2.to(u.m), 'ro', markersize=8)
    m.plot(ax3.to(u.m), by3.to(u.m), 'b')
    m.plot(ax4.to(u.m), by4.to(u.m), 'b')
    m.plot(ax5.to(u.m), by5.to(u.m), 'r--')
    m.plot(ax6.to(u.m), by6.to(u.m), 'r--')

    fig = plt.gcf()
    fig.set_size_inches(18.0, 15.0)
    plt.title('-{} D={}- dots each 1000km or {:.2f} <> offsets (mas): {:.1f}, {:.1f}\n'.format(obj, tamanho, np.absolute(1000*u.km/vel[idx]), off_ra[idx].value, off_de[idx].value), fontsize=25, fontproperties='FreeMono')
    plt.xlabel('\n year-m-d    h:m:s UT     ra__dec__J2000__candidate    C/A    P/A    vel   Delta  R*   K*  long\n\
{}  {:02d} {:02d} {:07.4f} {:+02d} {:02d} {:06.3f} {:6.3f} {:6.2f} {:6.2f} {:5.2f} {:5.1f} {:4.1f}  {:3.0f}'
        .format(datas[idx].iso, dados['afh'][idx], dados['afm'][idx], dados['afs'][idx], dados['ded'][idx], dados['dem'][idx], dados['des'][idx], ca[idx].value, pa[idx].value, dados['vel'][idx],
        dist[idx].value, dados['mR'][idx], dados['mK'][idx], dados['long'][idx]), fontsize=21, fontproperties='FreeMono')
    plt.savefig('{}_{}.png'.format(obj, datas[idx].isot),dpi=100)
    print 'Gerado: {}_{}.png'.format(obj, datas[idx].isot)
    plt.clf()
Beispiel #5
0
def plot():
    import numpy as np
    from mpl_toolkits.basemap import Basemap
    import matplotlib.pyplot as plt
    from datetime import datetime
    # miller projection
    # map = Basemap(projection='mill',lon_0=180)
    map = Basemap(projection='kav7',lon_0=180)
    
    # plot coastlines, draw label meridians and parallels.
    map.drawcoastlines()
    map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0])
    map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1])
    # fill continents 'coral' (with zorder=0), color wet areas 'aqua'
    map.drawmapboundary(fill_color='aqua')
    map.fillcontinents(color='coral',lake_color='aqua')
    # shade the night areas, with alpha transparency so the
    # map shows through. Use current time in UTC.
    date = datetime.utcnow()
    CS=map.nightshade(date)
    plt.title('Day/Night Map for %s (UTC)' % date.strftime("%d %b %Y %H:%M:%S"))
    plt.show()
# line1 = 'ISS (ZARYA)'
# line2 = '1 25544U 98067A   19015.25189318  .00000401  00000-0  13432-4 0  9995' # noqa
# line3 = '2 25544  51.6418  41.9123 0002387 289.9764 167.0424 15.53761231151490' # noqa

iss_pos = ephem.readtle(line1, line2, line3)

fig = plt.figure(figsize=(8, 6), edgecolor='w')
map = Basemap(projection='mill', lon_0=0)
map.drawcoastlines()
map.drawparallels(np.arange(-90, 90, 30), labels=[1, 0, 0, 0])
map.drawmeridians(np.arange(map.lonmin, map.lonmax + 30, 60),
                  labels=[0, 0, 0, 1])
map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='coral', lake_color='aqua')
map.nightshade(datetime.utcnow())

# 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',
Beispiel #7
0
def geramapa(idx):

    lons1, lats1, lons2, lats2 = calcfaixa(idx)

    lon = stars[idx].ra - datas[idx].sidereal_time('mean', 'greenwich')

    m = Basemap(projection='ortho',lat_0=stars[idx].dec.value,lon_0=lon.value,resolution=resolution)
#    m = Basemap(projection='ortho',lat_0=stars[idx].dec.value,lon_0=lon.value,resolution=resolution, llcrnrx=-7000000,llcrnry=-7000000,urcrnrx=7000000,urcrnry=7000000)
    m.drawcoastlines(linewidth=0.5)
    m.drawcountries(linewidth=0.5)
    m.drawstates(linewidth=0.5)
    m.drawmeridians(np.arange(0,360,30))
    m.drawparallels(np.arange(-90,90,30))
    m.drawmapboundary()
    ptcolor = 'black'
    lncolor = 'black'
    dscolor = 'black'
    if mapstyle == '2':
        m.drawmapboundary(fill_color='aqua')
        m.fillcontinents(color='coral',lake_color='aqua')
        ptcolor = 'red'
        lncolor = 'blue'
        dscolor = 'red'
    elif mapstyle == '3':
        m.shadedrelief()
        ptcolor = 'red'
        lncolor = 'blue'
        dscolor = 'red'
    elif mapstyle == '4':
        m.bluemarble()
        ptcolor = 'red'
        lncolor = 'red'
        dscolor = 'red'
    elif mapstyle == '5':
        m.etopo()
        ptcolor = 'red'
        lncolor = 'red'
        dscolor = 'red'
    if os.path.isfile(sitearq) == True:
        xpt,ypt = m(sites['lon'],sites['lat'])
        m.plot(xpt,ypt,'bo')
    CS=m.nightshade(datas[idx].datetime, alpha=0.2)
    a, b =m(lon.value, stars[idx].dec.value)
    a = a*u.m
    b = b*u.m
    dista = (dist[idx].to(u.km)*ca[idx].to(u.rad)).value*u.km
    disterr = (dist[idx].to(u.km)*erro.to(u.rad)).value*u.km
    vec = np.arange(0,7000,(np.absolute(vel[idx])*(60*u.s)).value)*u.km + np.absolute(vel[idx])*(60*u.s)
    vec = np.concatenate((vec.value,-vec.value), axis=0)*u.km
    ax = a + dista*np.sin(pa[idx])
    ax2 = ax + vec*np.cos(pa[idx])
    ax3 = ax2 - tamanho/2*np.sin(pa[idx])
    ax4 = ax2 + tamanho/2*np.sin(pa[idx])
    ax5 = a + (dista-disterr)*np.sin(pa[idx]) + vec*np.cos(pa[idx])
    ax6 = a + (dista+disterr)*np.sin(pa[idx]) + vec*np.cos(pa[idx])
    by = b + dista*np.cos(pa[idx])
    by2 = by - vec*np.sin(pa[idx])
    by3 = by2 - tamanho/2*np.cos(pa[idx])
    by4 = by2 + tamanho/2*np.cos(pa[idx])
    by5 = b + (dista-disterr)*np.cos(pa[idx]) - vec*np.sin(pa[idx])
    by6 = b + (dista+disterr)*np.cos(pa[idx]) - vec*np.sin(pa[idx])
    xs, ys = m(lons1, lats1)
    xs = [i for i in xs if i < 1e+30]
    ys = [i for i in ys if i < 1e+30]
    m.plot(xs, ys, 'b')
    xt, yt = m(lons2, lats2)
    xt = [i for i in xt if i < 1e+30]
    yt = [i for i in yt if i < 1e+30]
    m.plot(xt, yt, 'b')
#    m.plot(ax,by, 'o', color=ptcolor, markersize=mapsize[0].value*20/46)
#    m.plot(ax2.to(u.m),by2.to(u.m), 'o', color=ptcolor, markersize=mapsize[0].value*8/46)
#    m.plot(ax3.to(u.m), by3.to(u.m), color=lncolor)
#    m.plot(ax4.to(u.m), by4.to(u.m), color=lncolor)
#    m.plot(ax5.to(u.m), by5.to(u.m), '--', color=dscolor, label='+-{} error'.format(erro))
#    m.plot(ax6.to(u.m), by6.to(u.m), '--', color=dscolor)
#    plt.legend(fontsize=mapsize[0].value*21/46)

    fig = plt.gcf()
    fig.set_size_inches(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value)
    plt.title('-{} D={}- dots each 60 s <> offsets (mas): obj=({:.1f},{:.1f}), star=({:.1f},{:.1f})\n'
        .format(obj, tamanho, ob_off_ra[idx].value, ob_off_de[idx].value, st_off_ra[idx].value, st_off_de[idx].value), fontsize=mapsize[0].value*25/46, fontproperties='FreeMono', weight='bold')
    plt.xlabel('\n year-m-d    h:m:s UT     ra__dec__J2000__candidate    C/A    P/A    vel   Delta   R*   K*  long\n\
{}  {:02d} {:02d} {:07.4f} {:+02d} {:02d} {:06.3f} {:6.3f} {:6.2f} {:6.2f}  {:5.2f} {:5.1f} {:4.1f}  {:3.0f}'
        .format(datas[idx].iso, int(stars[idx].ra.hms.h), int(stars[idx].ra.hms.m), stars[idx].ra.hms.s, int(stars[idx].dec.dms.d), np.absolute(int(stars[idx].dec.dms.m)), np.absolute(stars[idx].dec.dms.s),
        ca[idx].value, pa[idx].value, vel[idx].value, dist[idx].value, magR[idx], magK[idx], longi[idx]), fontsize=mapsize[0].value*21/46, fontproperties='FreeMono', weight='bold')
    plt.savefig('{}_{}.png'.format(obj, datas[idx].isot),dpi=100)
    print 'Gerado: {}_{}.png'.format(obj, datas[idx].isot)
    plt.clf()
Beispiel #8
0
def geramapa(delt):
    deltatime = delt * u.s
    datas1 = datas[idx] + TimeDelta(deltatime)
    datas1.delta_ut1_utc = 0
    lon = stars[idx].ra - datas1.sidereal_time('mean', 'greenwich')

    m = Basemap(projection='ortho',
                lat_0=stars[idx].dec.value,
                lon_0=lon.value,
                resolution=resolution)
    #    m = Basemap(projection='ortho',lat_0=stars[idx].dec.value,lon_0=lon.value,resolution=resolution, llcrnrx=-7000000,llcrnry=-7000000,urcrnrx=7000000,urcrnry=7000000)
    m.drawcoastlines(linewidth=0.5)
    m.drawcountries(linewidth=0.5)
    m.drawstates(linewidth=0.5)
    m.drawmeridians(np.arange(0, 360, 30))
    m.drawparallels(np.arange(-90, 90, 30))
    m.drawmapboundary()
    ptcolor = 'black'
    lncolor = 'black'
    dscolor = 'black'
    if mapstyle == '2':
        m.drawmapboundary(fill_color='aqua')
        m.fillcontinents(color='coral', lake_color='aqua')
        ptcolor = 'red'
        lncolor = 'blue'
        dscolor = 'red'
    elif mapstyle == '3':
        m.shadedrelief()
        ptcolor = 'red'
        lncolor = 'blue'
        dscolor = 'red'
    elif mapstyle == '4':
        m.bluemarble()
        ptcolor = 'red'
        lncolor = 'red'
        dscolor = 'red'
    elif mapstyle == '5':
        m.etopo()
        ptcolor = 'red'
        lncolor = 'red'
        dscolor = 'red'
    if os.path.isfile(sitearq) == True:
        xpt, ypt = m(sites['lon'], sites['lat'])
        m.plot(xpt, ypt, 'bo')
    CS = m.nightshade(datas1.datetime, alpha=0.2)
    a, b = m(lon.value, stars[idx].dec.value)
    a = a * u.m
    b = b * u.m
    dista = (dist[idx].to(u.km) * ca[idx].to(u.rad)).value * u.km
    disterr = (dist[idx].to(u.km) * erro.to(u.rad)).value * u.km
    ax = a + dista * np.sin(pa[idx]) + (deltatime * vel[idx]) * np.cos(pa[idx])
    by = b + dista * np.cos(pa[idx]) - (deltatime * vel[idx]) * np.sin(pa[idx])
    m.plot(ax, by, 'o', color=ptcolor, markersize=mapsize[0].value * 20 / 46)
    #    plt.legend(fontsize=mapsize[0].value*21/46)

    fig = plt.gcf()
    fig.set_size_inches(mapsize[0].to(u.imperial.inch).value,
                        mapsize[1].to(u.imperial.inch).value)
    plt.title(
        '-{} D={}- dots each 60 s <> offsets (mas): obj=({:.1f},{:.1f}), star=({:.1f},{:.1f})\n'
        .format(obj, tamanho, ob_off_ra[idx].value, ob_off_de[idx].value,
                st_off_ra[idx].value, st_off_de[idx].value),
        fontsize=mapsize[0].value * 25 / 46,
        fontproperties='FreeMono',
        weight='bold')
    plt.xlabel(
        '\n year-m-d    h:m:s UT     ra__dec__J2000__candidate    C/A    P/A    vel   Delta   R*   K*  long\n\
{}  {:02d} {:02d} {:07.4f} {:+02d} {:02d} {:06.3f} {:6.3f} {:6.2f} {:6.2f}  {:5.2f} {:5.1f} {:4.1f}  {:3.0f}'
        .format(datas1.iso, int(stars[idx].ra.hms.h), int(stars[idx].ra.hms.m),
                stars[idx].ra.hms.s, int(stars[idx].dec.dms.d),
                np.absolute(int(stars[idx].dec.dms.m)),
                np.absolute(stars[idx].dec.dms.s), ca[idx].value,
                pa[idx].value, vel[idx].value, dist[idx].value, magR[idx],
                magK[idx], longi[idx]),
        fontsize=mapsize[0].value * 21 / 46,
        fontproperties='FreeMono',
        weight='bold')
    plt.savefig('{}_{:05d}.png'.format(obj,
                                       np.where(g == delt)[0][0] + 1),
                dpi=100)
    print 'Gerado: {}_{:05d}.png'.format(obj, np.where(g == delt)[0][0] + 1)
    plt.clf()
Beispiel #9
0
def geramapa(idx):
    lon = stars[idx].ra - datas[idx].sidereal_time('mean', 'greenwich')

    m = Basemap(projection='ortho',
                lat_0=stars[idx].dec.value,
                lon_0=lon.value,
                resolution='l')
    # draw coastlines, country boundaries, fill continents.
    m.shadedrelief()
    m.drawcoastlines(linewidth=0.25)
    m.drawcountries(linewidth=0.4)
    m.drawstates(linewidth=0.4)
    #m.fillcontinents(color='coral',lake_color='aqua')
    # draw the edge of the map projection region (the projection limb)
    #m.drawmapboundary(fill_color='aqua')
    # draw lat/lon grid lines every 30 degrees.
    m.drawmeridians(np.arange(0, 360, 30))
    m.drawparallels(np.arange(-90, 90, 30))
    if os.path.isfile(sitearq) == True:
        xpt, ypt = m(sites['lon'], sites['lat'])
        m.plot(xpt, ypt, 'bo')
    CS = m.nightshade(datas[idx].datetime, alpha=0.2)
    a, b = m(lon.value, stars[idx].dec.value)
    a = a * u.m
    b = b * u.m
    dista = (dist[idx].to(u.km) * ca[idx].to(u.rad)).value * u.km
    disterr = (dist[idx].to(u.km) * erro.to(u.rad)).value * u.km
    ax = a + dista * np.sin(pa[idx])
    ax2 = ax + 1000 * u.km * vec * np.cos(pa[idx])
    ax3 = ax2 - tamanho / 2 * np.sin(pa[idx])
    ax4 = ax2 + tamanho / 2 * np.sin(pa[idx])
    ax5 = a + (dista - disterr) * np.sin(pa[idx]) + 1000 * u.km * vec * np.cos(
        pa[idx])
    ax6 = a + (dista + disterr) * np.sin(pa[idx]) + 1000 * u.km * vec * np.cos(
        pa[idx])
    by = b + dista * np.cos(pa[idx])
    by2 = by - 1000 * u.km * vec * np.sin(pa[idx])
    by3 = by2 - tamanho / 2 * np.cos(pa[idx])
    by4 = by2 + tamanho / 2 * np.cos(pa[idx])
    by5 = b + (dista - disterr) * np.cos(pa[idx]) - 1000 * u.km * vec * np.sin(
        pa[idx])
    by6 = b + (dista + disterr) * np.cos(pa[idx]) - 1000 * u.km * vec * np.sin(
        pa[idx])
    m.plot(ax, by, 'ro', markersize=20)
    m.plot(ax2.to(u.m), by2.to(u.m), 'ro', markersize=8)
    m.plot(ax3.to(u.m), by3.to(u.m), 'b')
    m.plot(ax4.to(u.m), by4.to(u.m), 'b')
    m.plot(ax5.to(u.m), by5.to(u.m), 'r--')
    m.plot(ax6.to(u.m), by6.to(u.m), 'r--')

    fig = plt.gcf()
    fig.set_size_inches(18.0, 15.0)
    plt.title(
        '-{} D={}- dots each 1000km or {:.2f} <> offsets (mas): {:.1f}, {:.1f}\n'
        .format(obj, tamanho, np.absolute(1000 * u.km / vel[idx]),
                off_ra[idx].value, off_de[idx].value),
        fontsize=25,
        fontproperties='FreeMono')
    plt.xlabel(
        '\n year-m-d    h:m:s UT     ra__dec__J2000__candidate    C/A    P/A    vel   Delta  R*   K*  long\n\
{}  {:02d} {:02d} {:07.4f} {:+02d} {:02d} {:06.3f} {:6.3f} {:6.2f} {:6.2f} {:5.2f} {:5.1f} {:4.1f}  {:3.0f}'
        .format(datas[idx].iso, dados['afh'][idx], dados['afm'][idx],
                dados['afs'][idx], dados['ded'][idx], dados['dem'][idx],
                dados['des'][idx], ca[idx].value, pa[idx].value,
                dados['vel'][idx], dist[idx].value, dados['mR'][idx],
                dados['mK'][idx], dados['long'][idx]),
        fontsize=21,
        fontproperties='FreeMono')
    plt.savefig('{}_{}.png'.format(obj, datas[idx].isot), dpi=100)
    print 'Gerado: {}_{}.png'.format(obj, datas[idx].isot)
    plt.clf()
Beispiel #10
0
# your code here

# <headingcell level=1>

# Advanced Features

# <codecell>

from datetime import datetime
m = Basemap(projection='mill', lon_0=180)
m.drawmapboundary(fill_color='royalblue')
m.drawcoastlines()
m.fillcontinents()
m.drawcountries()
CS = m.nightshade(datetime.utcnow())

# <headingcell level=2>

# Great circles

# <codecell>

from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt

# setup lambert azimuthal map projection.
# create new figure
fig=plt.figure()
m = Basemap(llcrnrlon=-100.,llcrnrlat=20.,urcrnrlon=20.,urcrnrlat=60.,\
Beispiel #11
0
def geramapa(star,
             data,
             title,
             labelx,
             nameimg,
             mapstyle='1',
             resolution='l',
             centermap=None,
             lats=None,
             erro=None,
             ring=None,
             atm=None,
             clat=None,
             sitearq=None,
             fmt='png',
             dpi=100,
             mapsize=None):
    lon = star.ra - data.sidereal_time('mean', 'greenwich')
    center_map = EarthLocation(lon.value, star.dec.value)
    if not centermap == None:
        center_map = EarthLocation(centermap[0], centermap[1])
    m = Basemap(projection='ortho',
                lat_0=center_map.latitude.value,
                lon_0=center_map.longitude.value,
                resolution=resolution)
    #    m = Basemap(projection='ortho',lat_0=center_map.latitude.value,lon_0=center_map.longitude.value,resolution=resolution,llcrnrx=-2000000.,llcrnry=-1500000.,urcrnrx=2000000.,urcrnry=1500000.)
    #    kx = fig.add_axes([-0.003,-0.001,1.006,1.002])
    #    kx.set_rasterization_zorder(1)
    m.nightshade(data.datetime, alpha=0.2, zorder=0.5)
    m.drawcoastlines(linewidth=0.5)
    m.drawcountries(linewidth=0.5)
    m.drawstates(linewidth=0.5)
    m.drawmeridians(np.arange(0, 360, 30))
    m.drawparallels(np.arange(-90, 90, 30))
    m.drawmapboundary()
    style = {
        '1': {
            'ptcolor': 'red',
            'lncolor': 'blue',
            'ercolor': 'blue',
            'rncolor': 'blue',
            'atcolor': 'blue'
        },
        '2': {
            'ptcolor': 'red',
            'lncolor': 'blue',
            'ercolor': 'red',
            'rncolor': 'black',
            'atcolor': 'black'
        },
        '3': {
            'ptcolor': 'red',
            'lncolor': 'blue',
            'ercolor': 'red',
            'rncolor': 'black',
            'atcolor': 'black'
        },
        '4': {
            'ptcolor': 'red',
            'lncolor': 'red',
            'ercolor': 'red',
            'rncolor': 'black',
            'atcolor': 'black'
        },
        '5': {
            'ptcolor': 'red',
            'lncolor': 'red',
            'ercolor': 'red',
            'rncolor': 'black',
            'atcolor': 'black'
        }
    }
    if mapstyle == '2':
        m.drawmapboundary(fill_color='aqua')
        m.fillcontinents(color='coral', lake_color='aqua')
    elif mapstyle == '3':
        m.shadedrelief()
    elif mapstyle == '4':
        m.bluemarble()
    elif mapstyle == '5':
        m.etopo()
    if not lats == None:
        xs, ys = m(lats[0], lats[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, color=style[mapstyle]['lncolor'])
        xt, yt = m(lats[2], lats[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, color=style[mapstyle]['lncolor'])
    if not erro == None:
        xs, ys = m(erro[0], erro[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, '--', color=style[mapstyle]['ercolor'])
        xt, yt = m(erro[2], erro[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, '--', color=style[mapstyle]['ercolor'])
    if not ring == None:
        xs, ys = m(ring[0], ring[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, '--', color=style[mapstyle]['rncolor'])
        xt, yt = m(ring[2], ring[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, '--', color=style[mapstyle]['rncolor'])
    if not atm == None:
        xs, ys = m(atm[0], atm[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, color=style[mapstyle]['atcolor'])
        xt, yt = m(atm[2], atm[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, color=style[mapstyle]['atcolor'])
    if not clat == None:
        xc, yc = m(clon, clat)
        labe = [lab[i] for i in np.arange(len(lab)) if xc[i] < 1e+30]
        xc = [i for i in xc if i < 1e+30]
        yc = [i for i in yc if i < 1e+30]
        m.plot(xc, yc, 'o', color=style[mapstyle]['ptcolor'])


#    m.plot(ax,by, 'o', color=ptcolor, markersize=int(mapsize[0].value*20/46))
#    m.plot(ax2.to(u.m),by2.to(u.m), 'o', color=ptcolor, markersize=int(mapsize[0].value*12/46))
#    m.plot(ax3.to(u.m), by3.to(u.m), color='red')
#    m.plot(ax4.to(u.m), by4.to(u.m), color='red')
#    m.quiver(a-0*u.m,b-600000*u.m, 20, 0, width=0.005)

#    ax2 = a + dista*np.sin(pa) + [(i - datas).sec for i in temposplot]*u.s*vel*np.cos(paplus)
#    by2 = b + dista*np.cos(pa) - [(i - datas).sec for i in temposplot]*u.s*vel*np.sin(paplus)
#
#    labels = [i.iso.split()[1][0:8] for i in temposplot]
#    m.plot(ax2, by2, 'ro')

#    for label, axpt, bypt in zip(labe, xc, yc):
#        kx.text(axpt + 0, bypt + 350000, label, rotation=60, weight='bold')

#    if os.path.isfile(sitearq) == True:
#        xpt,ypt = m(sites['lon'],sites['lat'])
#        m.plot(xpt,ypt,'bo')
#        offset = [[xpt[0] + 100000,xpt[0] + 100000,xpt[0] + 100000,xpt[3] + 400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000],[10000,-30000,-60000,70000,30000,-20000,-70000,-30000,-70000]]
#        for i in np.arange(len(xpt)):
#            ax.text(offset[0][i],ypt[i]+offset[1][i],sites['nome'][i], weight='bold')

#    m.plot(ax5.to(u.m), by5.to(u.m), '--', color=dscolor, label='+-{} error'.format(erro))
#    m.plot(ax6.to(u.m), by6.to(u.m), '--', color=dscolor)
#    plt.legend(fontsize=mapsize[0].value*21/46)

    fig = plt.gcf()
    fig.set_size_inches(mapsize[0].to(u.imperial.inch).value,
                        mapsize[1].to(u.imperial.inch).value)
    plt.title(title,
              fontsize=mapsize[0].value * 25 / 46,
              fontproperties='FreeMono',
              weight='bold')
    plt.xlabel(labelx,
               fontsize=mapsize[0].value * 21 / 46,
               fontproperties='FreeMono',
               weight='bold')
    plt.savefig('{}.{}'.format(nameimg, fmt), format=fmt, dpi=dpi)
    print 'Gerado: {}.{}'.format(nameimg, fmt)
    plt.clf()
Beispiel #12
0
    def __init__(self, in_file,
                    vg_files = [1],
                    data_type = 1,
                    projection = 'cyl',
                    color_map = 'jet',
                    face_colour = "white",
                    time_zone = 0,
                    filled_contours = False,
                    plot_contours = False,
                    plot_center = 't',
                    plot_meridians = True,
                    plot_parallels = True,
                    plot_nightshade = True,
                    resolution = 'c',
                    points_of_interest = [],
                    save_file = '',
                    run_quietly = False,
                    dpi = 150,
                    parent = None,
                    datadir=None):

        self.run_quietly = run_quietly
        self.dpi=float(dpi)

        self.datadir = datadir

        try:
            plot_parameters = VOAFile((in_file))
            plot_parameters.parse_file()
        except zipfile.BadZipFile as e:
            if parent is None:
                print("Invalid .vgz file")
                sys.exit(1)

        if (plot_parameters.get_projection() != 'cyl'):
            print(_("Error: Only lat/lon (type 1) input files are supported"))
            sys.exit(1)

        grid = plot_parameters.get_gridsize()
        self.image_defs = VOAAreaPlot.IMG_TYPE_DICT[int(data_type)]

        # TODO This needs a little more work... what if the pcenter card is not specified

        if plot_center == 'p':
            plot_centre_location = plot_parameters.get_location(plot_parameters.P_CENTRE)
        else:
            plot_centre_location = plot_parameters.get_location(plot_parameters.TX_SITE)

        self.points_of_interest = [plot_centre_location]
        if len(points_of_interest) > 0:
            self.points_of_interest.extend(points_of_interest)

        imageBuf = np.zeros([grid, grid], float)

        area_rect = plot_parameters.get_area_rect()

        # The checks ought to be performed in the area_rect.
        # Do a few basic sanity checks #
        #if ( (area_rect.get_sw_lon() < -180) or (area_rect.get_ne_lon() > 180.0) or (area_rect.get_sw_lat() < -90) or (area_rect.get_ne_lat() > 90.0) ):
        #    print "Input file latitudes/longitudes are out of range"
        #    print "-180 < Latitude < 180.0, -90 < Longitude < 90"
        #    sys.exit(1)
        #if ( (area_rect.get_sw_lon() == area_rect.get_ne_lon()) or (area_rect.get_sw_lat() == area_rect.get_ne_lat()) ):
        #    print "Input file latitudes/longitudes are the same"
        #    print "-180 < Latitude < 180.0, -90 < Longitude < 90"
        #    sys.exit(1)

        colString = 'matplotlib.cm.'+color_map
        colMap = eval(colString)

        self.subplots = []
        self.number_of_subplots = len(vg_files)

        matplotlib.rcParams['axes.edgecolor'] = 'gray'
        matplotlib.rcParams['axes.facecolor'] = 'white'
        matplotlib.rcParams['figure.facecolor'] = face_colour
        #matplotlib.rcParams['figure.figsize'] = (6, 10)
        matplotlib.rcParams['figure.subplot.hspace'] = 0.45
        matplotlib.rcParams['figure.subplot.wspace'] = 0.35
        matplotlib.rcParams['figure.subplot.right'] = 0.85
        colorbar_fontsize = 12

        if self.number_of_subplots <= 1:
            self.num_rows = 1
            self.main_title_fontsize = 24
            matplotlib.rcParams['legend.fontsize'] = 12
            matplotlib.rcParams['axes.labelsize'] = 12
            matplotlib.rcParams['axes.titlesize'] = 10
            matplotlib.rcParams['xtick.labelsize'] = 10
            matplotlib.rcParams['ytick.labelsize'] = 10
            matplotlib.rcParams['figure.subplot.top'] = 0.8 # single figure plots have a larger title so require more space at the top.
        elif ((self.number_of_subplots >= 2) and (self.number_of_subplots <= 6 )):
            self.num_rows = 2
            self.main_title_fontsize = 18
            matplotlib.rcParams['legend.fontsize'] = 10
            matplotlib.rcParams['axes.labelsize'] = 10
            matplotlib.rcParams['axes.titlesize'] = 11
            matplotlib.rcParams['xtick.labelsize'] = 8
            matplotlib.rcParams['ytick.labelsize'] = 8
            #self.x_axes_ticks = P.arange(0,25,4)
        else:
            self.num_rows = 3
            self.main_title_fontsize = 16
            matplotlib.rcParams['legend.fontsize'] = 8
            matplotlib.rcParams['axes.labelsize'] = 8
            matplotlib.rcParams['axes.titlesize'] = 10
            matplotlib.rcParams['xtick.labelsize'] = 6
            matplotlib.rcParams['ytick.labelsize'] = 6
            #self.x_axes_ticks = P.arange(0,25,4)

        self.num_cols = int(math.ceil(float(self.number_of_subplots)/float(self.num_rows)))
        self.fig=Figure()
        self.main_title_label = self.fig.suptitle(str(self.image_defs['title']), fontsize=self.main_title_fontsize)

        if projection == 'ortho':
            self.show_subplot_frame = False

        for plot_ctr, vg_file in enumerate(vg_files):
            points = np.zeros([grid,grid], float)

            lons = np.arange(area_rect.get_sw_lon(), area_rect.get_ne_lon()+0.001,(area_rect.get_ne_lon()-area_rect.get_sw_lon())/float(grid-1))
            lons[-1] = min(180.0, lons[-1])
            lats = np.arange(area_rect.get_sw_lat(), area_rect.get_ne_lat()+0.001,(area_rect.get_ne_lat()-area_rect.get_sw_lat())/float(grid-1))
            lats[-1] = min(90.0, lats[-1])

            ax = self.fig.add_subplot(self.num_rows,
                    self.num_cols,
                    plot_ctr+1,
                    frame_on = self.show_subplot_frame,
                    axisbg = 'white')

            self.subplots.append(ax)

            ax.label_outer()
            if in_file.endswith('.vgz'):
                base_filename = get_base_filename(in_file)
                zf = zipfile.ZipFile(in_file)
                vgFile = io.TextIOWrapper(zf.open("{:s}.vg{:d}".format(base_filename, vg_file)), 'utf-8')
            else:
                vgFile = open("{:s}.vg{:d}".format(os.path.splitext(in_file)[0], vg_file))
            pattern = re.compile(r"[a-z]+")

            for line in vgFile:
                match = pattern.search( line )
                if not match:
                    value = float(line[int(self.image_defs['first_char']):int(self.image_defs['last_char'])])
                    # TODO Does this need to be normalised here if it's also being done in the plot?
                    value = max(self.image_defs['min'], value)
                    value = min(self.image_defs['max'], value)
                    points[int(line[3:6])-1][int(line[0:3])-1] = value
            vgFile.close()
            if 'zf' in locals():
                zf.close()

            m_args={}
            if projection in ('cyl', 'mill', 'gall'):
                m_args.update({"llcrnrlon":area_rect.get_sw_lon(),
                    "llcrnrlat":area_rect.get_sw_lat(),
                    "urcrnrlon":area_rect.get_ne_lon(),
                    "urcrnrlat":area_rect.get_ne_lat()})

            if projection in ('robin', 'vandg', 'sinu', 'mbtfpq', 'eck4',
                            'kav7', 'moll', 'hammer', 'gnom',
                            'laea', 'aeqd', 'cea', 'merc'):
                m_args.update({"lat_0":plot_centre_location.get_latitude(),
                    "lon_0":plot_centre_location.get_longitude()})
                if projection in ('cea', 'merc'):
                    m_args['lat_ts']=0

            m = Basemap(ax=ax, projection=projection, resolution=resolution, **m_args)

            m.drawcoastlines(color='black')
            m.drawcountries(color='grey')
            m.drawmapboundary(color='black', linewidth=1.0)

            #points = np.clip(points, self.image_defs['min'], self.image_defs['max'])
            #colMap.set_under(color ='k', alpha=0.0)
            lons, lats  = np.meshgrid(lons, lats)
            points = np.clip(points, self.image_defs['min'], self.image_defs['max'])
            if (filled_contours):
                im = m.contourf(lons, lats, points, self.image_defs['y_labels'],
                    latlon=True,
                    cmap = colMap)
                plot_contours = True
            else:
                im = m.pcolormesh(lons, lats, points,
                    latlon=True,
                    vmin = self.image_defs['min'],
                    vmax = self.image_defs['max'],
                    cmap = colMap,
                    shading='gouraud')

            if plot_contours:
                ct = m.contour(lons, lats, points, self.image_defs['y_labels'][1:],
                    latlon=True,
                    linestyles='solid',
                    linewidths=0.5,
                    colors='k',
                    vmin=self.image_defs['min'],
                    vmax=self.image_defs['max'] )

            #######################
            # Plot greyline
            #######################
            if plot_nightshade:
                m.nightshade(plot_parameters.get_daynight_datetime(vg_files[plot_ctr]-1))


            ##########################
            # Points of interest
            ##########################
            for location in self.points_of_interest:
                if area_rect.contains(location.get_latitude(), location.get_longitude()):
                    xpt,ypt = m(location.get_longitude(),location.get_latitude())
                    ax.plot([xpt],[ypt],'ro')
                    ax.text(xpt+100000,ypt+100000,location.get_name())

            if plot_meridians:
                if (area_rect.get_lon_delta() <= 90.0):
                    meridians = np.arange(-180, 190.0, 10.0)
                elif (area_rect.get_lon_delta() <= 180.0):
                    meridians = np.arange(-180.0, 210.0, 30.0)
                else:
                    meridians = np.arange(-180, 240.0, 60.0)
                if ((projection == 'ortho')    or (projection == 'vandg')):
                    m.drawmeridians(meridians)
                else:
                    m.drawmeridians(meridians,labels=[1,1,0,1])

            if plot_parallels:
                if (area_rect.get_lat_delta() <= 90.0):
                    parallels = np.arange(-90.0, 120.0, 60.0)
                else:
                    parallels = np.arange(-90.0, 120.0, 30.0)
                if ((projection == 'ortho')    or (projection == 'vandg')):
                    m.drawparallels(parallels)
                else:
                    m.drawparallels(parallels,labels=[1,1,0,1])


            #add a title
            title_str = plot_parameters.get_plot_description_string(vg_files[plot_ctr]-1, self.image_defs['plot_type'], time_zone)
            if self.number_of_subplots == 1:
                title_str = plot_parameters.get_plot_description_string(vg_files[plot_ctr]-1, self.image_defs['plot_type'], time_zone)
                title_str = title_str + "\n" + plot_parameters.get_detailed_plot_description_string(vg_files[plot_ctr]-1)
            else :
                title_str = plot_parameters.get_minimal_plot_description_string(vg_files[plot_ctr]-1, self.image_defs['plot_type'], time_zone)
            self.subplot_title_label = ax.set_title(title_str)

        # Add a colorbar on the right hand side, aligned with the
        # top of the uppermost plot and the bottom of the lowest
        # plot.
        # create an axes on the right side of ax. The width of cax will be 5%
        # of ax and the padding between cax and ax will be fixed at 0.05 inch.
        if self.number_of_subplots > 1:
            self.cb_ax = self.fig.add_axes(self.get_cb_axes())
        else:
            divider = make_axes_locatable(ax)
            self.cb_ax = divider.append_axes("right", size="5%", pad=0.05)

        self.fig.colorbar(im, cax=self.cb_ax,
                    orientation='vertical',
                    ticks=self.image_defs['y_labels'],
                    format = FuncFormatter(eval('self.'+self.image_defs['formatter'])))

        #print self.image_defs['y_labels']
        for t in self.cb_ax.get_yticklabels():
            t.set_fontsize(colorbar_fontsize)

        #self.fig.tight_layout()
        canvas = FigureCanvas(self.fig)
        self.fig.canvas.mpl_connect('draw_event', self.on_draw)
        canvas.show()

        if save_file :
            self.save_plot(canvas, save_file)

        #todo this ought to a command line param
        if not self.run_quietly:
            dia = VOAPlotWindow('pythonProp - ' + self.image_defs['title'], canvas, parent=parent, datadir=self.datadir)
        return
Beispiel #13
0
def FoV_selections(sim_file,
                   lattice_files,
                   datetime,
                   centre,
                   map_bkgd='bluemarble',
                   out='show',
                   **mission_params):
    """
    Plots the fields of view chosen by the intelligent pointing algorithm onto a map.
    
    Args:
    - sim_file: GMAT output file path to use
    - lattice_files: list - List of lattice files used for the mission
    - datetime: dt.datetime instance - Time at which to plot points
    - center: tuple: (latitude, longitude) to be used as the center of an orthographic projection
    - map_bkgd: Background to plot on the map
    - out: either 'save' or 'show. Saves or shows the figure
    
    mission_params:
    - kwargs for retrievals.Mission instance.
    """

    mission = retrievals.Mission(sim_file, *lattice_files, **mission_params)

    obs_time = time_utils.Time(datetime, mission.satellite.times[0].ref)

    # find the closest apogee point to obs_time
    apogees = mission.satellite.get_apogees()
    apogee_ind = time_utils.closest_index(obs_time, apogees)

    # create the ObservationPeriod instance, and generate the Retrieval instances
    obs = retrievals.ObservationPeriod(
        mission, apogees[apogee_ind],
        mission.lattice_files[apogee_ind % len(lattice_files)])
    obs.main_filter()
    obs.generate_retrievals()
    print(len(obs.retrievals))

    # find the closest segment of the observation period
    obs_ind = time_utils.closest_index(obs_time, obs.obs_middle)

    proj_cld = Basemap(projection='ortho',
                       lat_0=centre[0],
                       lon_0=centre[1],
                       resolution='c')
    proj_cld.drawcoastlines()
    proj_cld.drawcountries()
    # draw cloud data that was used to determine FOV locations
    obs.cloud_collection.show_clouds_ortho(obs.cloud_times[obs_ind],
                                           centre,
                                           map_bkgd=map_bkgd,
                                           out='')

    proj_cld.nightshade(datetime)

    # draw a red border around each of the selected FOVs
    for ret in obs.retrievals[obs_ind]:

        lats = np.concatenate([
            ret.pixel_lats[:, 0], ret.pixel_lats[-1, :],
            ret.pixel_lats[::-1, -1], ret.pixel_lats[0, ::-1]
        ])
        lons = np.concatenate([
            ret.pixel_lons[:, 0], ret.pixel_lons[-1, :],
            ret.pixel_lons[::-1, -1], ret.pixel_lons[0, ::-1]
        ])

        x, y = proj_cld(lons, lats)
        coords = np.vstack([x, y]).T

        if not np.sum(coords > 1e15):

            p = Polygon(coords, fill=False, edgecolor='r', zorder=10)
            plt.gca().add_patch(p)

    plt.title('FoV Selections {0} - {1} UTC'.format(
        obs.obs_times[obs_ind].strf('%d %B %Y %H:%M'),
        obs.obs_times[obs_ind + 1].strf('%H:%M')))

    if out == 'show':
        plt.show()
    elif out == '':
        pass
    else:
        plt.savefig(out)
        plt.close()
Beispiel #14
0
def plt_map(df, t0, tend, dt, out_path_map, data_dir):
    tmp_t = t0
    t = [0, 0]
    while (tmp_t < tend):
        time_loop0 = datetime.datetime.now()
        #	print tmp_t
        t1 = tmp_t
        t2 = tmp_t + datetime.timedelta(minutes=dt)
        print t1, t2

        #Sort the data by band and time, then group by band.
        srt = df.sort(['band', 'timestamp'])
        grouped = srt.groupby('band')

        # condition for selecting
        cond0 = ((df['timestamp'] > t1) & (df['timestamp'] < t2))
        # 		(df['rx_lat'] > 30) & (df['rx_lat'] < 70) &
        # 		(df['tx_lat'] > 30) & (df['tx_lat'] < 70) &
        # 		(df['rx_lon'] < 50) & (df['rx_lon'] > -20) &
        # 		(df['tx_lon'] < 50) & (df['tx_lon'] > -20) )

        # Set up a dictionary which identifies which bands we want and some plotting attributes for each band
        bands = {}
        bands[50] = {'name': '6 m / 50 MHz', 'color': 'red', 'i': 7, 'f': 50}
        bands[28] = {'name': '10 m / 28 MHz', 'color': 'pink', 'i': 5, 'f': 28}
        bands[21] = {
            'name': '15 m / 21 MHz',
            'color': 'orange',
            'i': 3,
            'f': 21
        }
        bands[14] = {
            'name': '20 m / 14 MHz',
            'color': 'yellow',
            'i': 1,
            'f': 14
        }
        bands[10] = {
            'name': '30 m / 10 MHz',
            'color': 'green',
            'i': 6,
            'f': 10
        }
        bands[7] = {'name': '40 m / 7 MHz', 'color': 'blue', 'i': 4, 'f': 7}
        bands[3] = {
            'name': '80 m / 3.5 MHz',
            'color': 'purple',
            'i': 2,
            'f': 3
        }
        bands[1] = {
            'name': '160 m / 1.5 MHz',
            'color': 'black',
            'i': 0,
            'f': 1
        }

        # Determine the aspect ratio of each histogram.
        xsize = 10.
        ysize = 2.5
        nx_plots = 2  # Let's just do 1 panel across.
        ny_plots = len(
            bands.keys()
        )  # But we will do a stackplot with one panel for each band of interest.

        fig = plt.figure(
            figsize=(nx_plots * xsize, ny_plots *
                     ysize))  # Create figure with the appropriate size.
        subplot_nr = 0  # Counter for the subplot
        xrng = (0, 5000)

        #make a color map
        # from http://stackoverflow.com/questions/9707676/defining-a-discrete-colormap-for-imshow-in-matplotlib
        colorList = [bands[x]['color'] for x in sorted(bands.keys())]
        cmap = colors.ListedColormap(colorList)
        bounds = [np.int(bands[x]['f']) for x in sorted(bands.keys())]
        bounds.insert(0, 0)
        norm = colors.BoundaryNorm(bounds, cmap.N)
        cmap.set_over('0.25')
        cmap.set_under('0.75')

        # make basemap
        fig2 = plt.figure(figsize=(8, 8))

        gs = grd.GridSpec(2,
                          2,
                          width_ratios=[50, 1],
                          height_ratios=[1, 1],
                          wspace=0.1,
                          hspace=0.25)

        ax2 = plt.subplot(gs[0])
        ax3 = plt.subplot(gs[1])


        m = Basemap(llcrnrlon=-179.,llcrnrlat=-80.,urcrnrlon=179.,urcrnrlat=80,\
           rsphere=(6378137.00,6356752.3142),\
           resolution='i',projection='merc',\
           ax=ax2)
        m.drawcountries()
        m.drawcoastlines()
        m.drawstates()
        m.fillcontinents(color='#bbbbbf')
        CS = m.nightshade(t1)
        # draw parallels
        m.drawparallels(np.arange(-90, 90, 10), labels=[1, 1, 0, 1])
        # draw meridians
        m.drawmeridians(np.arange(-180, 180, 20), labels=[1, 1, 0, 1])

        ax2.set_title('WSPR Map: ' + t1.strftime('%d %b %Y %H%M UT - ') +
                      t2.strftime('%d %b %Y %H%M UT'))

        cb1 = mpl.colorbar.ColorbarBase(ax3,
                                        cmap=cmap,
                                        norm=norm,
                                        boundaries=bounds,
                                        spacing='uniform',
                                        orientation='vertical')
        cb1.set_label('Frequency (MHz)')
        plot_time = datetime.datetime.utcnow()
        txt_2 = ('Plotted: ' + plot_time.strftime('%d %b %Y %H%M UT'))

        ax2.set_xlabel('\n' + txt_2)

        gs00 = grd.GridSpecFromSubplotSpec(4, 2, subplot_spec=gs[2])

        #sys.exit()
        # want to include shareex somewhere in here...?
        for band_key in sorted(bands.keys(
        )):  # Now loop through the bands and create 1 histogram for each.

            #subplot_nr += 1 # Increment subplot number... it likes to start at 1.# do the calculation, cond0 is defined above
            subplot_nr = np.int(bands[band_key]['i'])
            print band_key, subplot_nr
            ax = plt.Subplot(fig2, gs00[subplot_nr])
            # ax      = fig2.add_subplot(ny_plots,nx_plots,subplot_nr)
            fig2.add_subplot(ax)
            dist = grouped.get_group(band_key)['dist'][cond0]
            bins_in = np.arange(0, 5000, 200)
            hist, bins_out = np.histogram(dist, bins=bins_in)
            #code from: http://stackoverflow.com/questions/17874063/is-there-a-parameter-in-matplotlib-pandas-to-have-the-y-axis-of-a-histogram-as-p
            ax.bar(bins_out[:-1],
                   hist.astype(np.float32),
                   width=(bins_out[1] - bins_out[0]),
                   color=bands[band_key]['color'],
                   label=bands[band_key]['name'])
            ax.set_ylim(0, 30)
            #    grouped.get_group(band_key)['dist'][cond0].hist(bin=bins_in,norm=True,
            #                ax=ax,color=bands[band_key]['color'],label=bands[band_key]['name']) #Pandas has a built-in wrapper for the numpy and matplotlib histogram function.
            ax.legend(loc='upper right')
            ax.set_xlim(xrng)
            ax.set_ylabel('WSPR Spots (#)')
            tx_lon = grouped.get_group(band_key)['tx_lon'][cond0].values
            rx_lon = grouped.get_group(band_key)['rx_lon'][cond0].values
            tx_lat = grouped.get_group(band_key)['tx_lat'][cond0].values
            rx_lat = grouped.get_group(band_key)['rx_lat'][cond0].values

            if (subplot_nr == 0) | (subplot_nr == 1):
                txt = []
                txt.append('WSPRNet Distances')
                txt.append(
                    t1.strftime('%d %b %Y %H%M UT - ') +
                    t2.strftime('%d %b %Y %H%M UT'))
                ax.set_title(
                    '\n'.join(txt)
                )  #\n creates a new line... here I'm joining two strings in a list to form a single string with \n as the joiner
            if subplot_nr == len(bands.keys()):
                txt_2 = ('Plotted: ' + plot_time.strftime('%d %b %Y %H%M UT'))
                ax.set_xlabel('WSPR Reported Distance [km]' + txt_2)

            # setup mercator map projection.

            print tx_lon

            map(partial(m.drawgreatcircle, color=bands[band_key]['color']),
                tx_lon, tx_lat, rx_lon, rx_lat)

        #fig2.tight_layout()  #This often cleans up subplot spacing when you have multiple panels.

    # 	filename    = os.path.join(out_path_hist,'%s.png' % t1.strftime('%H%MUT_WSPRHist') )
    #sys.exit()
    #fig.savefig(filename)#,bbox_inches='tight') # bbox_inches='tight' removes whitespace at the edge of the figure.  Very useful when creating PDFs for papers.
        file_map = os.path.join(out_path_map,
                                '%s.png' % t1.strftime('%m%d_%H%MUT'))  #Y%m%d
        fig2.savefig(file_map)  #, bbox_inches='tight')

        plt.close('all')
        tmp_t = tmp_t + datetime.timedelta(minutes=dt)

    # os.chdir(out_path_map)
# 	call(['ffmpeg', '-framerate', '4','-pattern_type','glob','-i', '*.png',
# 					 '-s:v','1280x720','-c:v','libx264','-profile:v','high',
# 					 '-crf','23','-pix_fmt','yuv420p','-r','30','%s.mp4'% t1.strftime('%m%d')])
#
# 	os.chdir(data_dir)
# out_files = os.path.join(out_path_hist,'*.png')
# out_mov = os.path.join(out_path_hist,'test.mp4')
# command1 = 'ffmpeg -framerate 4 -pattern_type glob  -i '+out_files+' -s:v 1280x720 -c:v libx264 -profile:v high -crf 23 -pix_fmt yuv420p -r 30 '+ out_mov
# call(command1, shell=True)
    time_1 = datetime.datetime.now()

    print 'Total processing time is %.1f s.' % (time_1 -
                                                time_0).total_seconds()
    return None
Beispiel #15
0
def animate_FoV(sim_file, lattice_files, date_range, map_bkgd='mask', out='show', **mission_params):
    print("animate_FOV")
    assert type(sim_file) == str
    assert type(lattice_files) == list
    assert type(date_range) == tuple
    """
    Creates an animation (avi file) of field-of-view selections and cloud cover over time for one satellite.
    
    Args: 
    
    - sim_file: GMAT output file path to use
    - lattice_file: list - List of lattice files used for the mission. Must be given in order of W-E, starting with the first apogee
    - date_range: tuple of dt.datetime instances - (start time, end time) tuple for the animation. Requires year, month, day, hour.
    - map_bkgd: Background to plot on the map
    - out: either 'save' or 'show. Saves or shows the figure
    
    mission_params:
    - kwargs for retrievals.Mission instance.
    
    """
    
    # Set up the mission instance and find the apogees
    mission = retrievals.Mission(sim_file, *lattice_files, **mission_params)
    apogees = mission.satellite.get_apogees()
    
    # Get the start and end times and convert them from dt.datetime instances to time_utils.Time instances
    start_time = time_utils.Time(date_range[0], mission.satellite.times[0].ref)
    end_time = time_utils.Time(date_range[1], mission.satellite.times[0].ref)
    
    
    # Get the indices of the first and last apogees relevant to the time period
    apogee_start_ind = time_utils.closest_index(start_time, apogees)
    apogee_last_ind = time_utils.closest_index(end_time, apogees)

    # Empty directory to store temporary images before making the animation
    temp_dir = '../figures/animation_temp' 
    if not os.path.exists(temp_dir):
        os.mkdir(temp_dir)
    
    # Generate a retrievals.ObservationPeriod instance for every apogee in the relevant time frame
    for k in range(apogee_start_ind, apogee_last_ind + 1):
        # create the ObservationPeriod instance, and generate the Retrieval instances
        if lattice_files == []:
            lat_file = None
        else:
            lat_file = mission.lattice_files[k%len(lattice_files)]
        obs = retrievals.ObservationPeriod(mission, apogees[k], lat_file)
        obs.main_filter()
        obs.generate_retrievals()
        
        # after this point we're just plotting stuff, no actual analysis
        col = 'xkcd:red'
        lat_0 = 90
        lon_0 = -95
        map_params = {"projection": 'ortho',
                    "lat_0": lat_0,
                    "lon_0": lon_0,
                    "resolution": 'c'}
        # Plot cloud data and pointing selections for each segment of each observation period
        for i in range(len(obs.retrievals)):
            
            proj_cld = Basemap(**map_params)
            
            # draw cloud data that was used to determine FOV locations
            obs.cloud_collection.show_clouds_ortho(
                obs.cloud_times[i], (lat_0, lon_0), map_bkgd=map_bkgd, out='')
            # Draw terminator
            proj_cld.nightshade(
                obs.obs_times[i].to_datetime64().astype(dt.datetime))
            
            # Draw a bullseye at the sub-satellite point
            satx, saty = proj_cld(obs.satlon[i], obs.satlat[i])
            inner = Circle(
                (satx,saty), radius=9e4, color=col, zorder=10)
            outer = Circle(
                (satx,saty), radius=2e5, linewidth=1.5, facecolor = 'k',
                edgecolor=col, zorder = 10 )
            plt.gca().add_patch(outer)
            plt.gca().add_patch(inner)
            
            for ret in obs.retrievals[i]:
                # draw a border around each of the selected FOVs
                lats = np.concatenate([ret.pixel_lats[:,0],
                    ret.pixel_lats[-1,:],
                    ret.pixel_lats[::-1,-1],
                    ret.pixel_lats[0,::-1]])
                lons = np.concatenate([ret.pixel_lons[:,0],
                    ret.pixel_lons[-1,:],
                    ret.pixel_lons[::-1,-1],
                    ret.pixel_lons[0,::-1]])
        
                x,y = proj_cld(lons, lats)
                coords = np.vstack([x,y]).T
                
                if not np.sum(coords > 1e15):
                    p = Polygon(coords, fill=False, edgecolor=col, zorder=10,
                        antialiased = True) 
                    plt.gca().add_patch(p)

            plt.title('{0} - {1} UTC'.format(
                obs.obs_times[i].strftime('%d %B %H:%M'),
                obs.obs_times[i+1].strftime('%H:%M')))
            # Save the figure in the temporary directory
            fname = 'FoVs{0}.png'.format(
                obs.obs_times[i].strftime('%y%m%d%H:%M'))
            fpath = os.path.join(temp_dir, fname)
            plt.savefig(fpath, dpi=500)
            print('Saved figure: {0}-{1}.png'.format(
                obs.obs_times[i].strftime('%m%d%Y%H:%M'),
                obs.obs_times[i+1].strftime('%H:%M')))
            #plt.show()
            plt.close()

    # Create an animation using all the temporary images
    os.system(('mencoder -o '
               '../figures/constellationview_{0}_{1}.avi '
               'mf://../figures/animation_temp/FoVs*.png '
               '-ovc lavc -lavcopts vcodec=msmpeg4v2 -mf '
               'fps=2').format(start_time.strftime('%y%m%d'),
                              end_time.strftime('%y%m%d')))
    # Delete the temporary images
    os.system('rm ../figures/animation_temp/*.png')
    os.system('rmdir ../figures/animation_temp')    
Beispiel #16
0
    def polar_quiver_wind(self, ax, ns='N'):
        # Wind vector in lat-long coordinates.
        # For different map projections, the arithmetics to calculate xywind
        # are different
        if self.empty:
            return
        from mpl_toolkits.basemap import Basemap
        from apexpy import Apex
        # Creat polar coordinates
        projection, fc = ('npstere', 1) if ns == 'N' else ('spstere', -1)
        m = Basemap(projection=projection,
                    boundinglat=fc * 40,
                    lon_0=0,
                    resolution='l')
        m.drawcoastlines(color='gray', zorder=1)
        m.fillcontinents(color='lightgray', zorder=0)
        dt = self.index.min() + (self.index.max() - self.index.min()) / 2
        m.nightshade(dt, zorder=2)
        #m.drawparallels(np.arange(-80,81,20))
        #m.drawmeridians(np.arange(-180,181,60),labels=[1,1,1,1])

        # Calculate mlat and mlon
        lat_grid = np.arange(-90, 91, 10)
        lon_grid = np.arange(-180, 181, 10)
        lon_grid, lat_grid = np.meshgrid(lon_grid, lat_grid)
        gm = Apex(date=2005)
        mlat, mlon = gm.convert(lat_grid, lon_grid, 'geo', 'apex')
        hc1 = m.contour(lon_grid,
                        lat_grid,
                        mlat,
                        levels=np.arange(-90, 91, 10),
                        colors='k',
                        zorder=3,
                        linestyles='dashed',
                        linewidths=1,
                        latlon=True)
        # hc2 = m.contour(lon_grid,lat_grid,mlon,levels=np.arange(-180,181,45),
        #                 colors='k', zorder=3, linestyles='dashed', latlon=True)
        plt.clabel(hc1, inline=True, colors='k', fmt='%d')
        # plt.clabel(hc2,inline=True,colors='k',fmt='%d')

        # Calculate and plot x and y winds
        lat = self.lat
        lon = self.long
        wind = self.wind
        winde1 = self.winde
        winde = winde1 * wind
        windn1 = self.windn
        windn = windn1 * wind
        # only appropriate for the npstere and spstere
        xwind = fc * winde * np.cos(lon / 180 * np.pi) - windn * np.sin(
            lon / 180 * np.pi)
        ywind = winde * np.sin(lon / 180 * np.pi) + fc * windn * np.cos(
            lon / 180 * np.pi)
        hq = m.quiver(np.array(lon),
                      np.array(lat),
                      xwind,
                      ywind,
                      color='blue',
                      scale=300,
                      scale_units='inches',
                      zorder=3,
                      latlon=True)
        #plt.quiverkey(hq,1.05,1.05,100,'100 m/s',coordinates='axes',labelpos='E')
        #m.scatter(np.array(lon),np.array(lat),
        #          s=50, c=self.index.to_julian_date(),linewidths=0, zorder=4,latlon=True)
        return m
def plotonmap(obs,
              sun_lat,
              sun_lon,
              city_lat,
              city_lon,
              city,
              projection='ortho',
              redraw=False,
              bluemarble=False):
    if os.path.exists("movies/%s.mp4" % city):
        return

    filename = "images/%s/plot_%s_00.png" % (
        city, obs.date.datetime().strftime("%Y%m%d"))

    if not redraw and os.path.exists(filename):
        return
    else:
        plt.style.use('dark_background')
        plt.figure(figsize=(19.2, 10.80))
        m = Basemap(projection=projection,
                    resolution='l',
                    lat_0=20,
                    lon_0=city_lon)
        m.bluemarble()

        # draw terminator
        _ = m.nightshade(
            obs.date.datetime(),
            delta=0.7,
            alpha=0.5,
        )

        # draw tropics and equator
        draw_parallel(m,
                      23.5,
                      city_lon,
                      color='ivory',
                      label="Tropic of\nCancer")
        draw_parallel(m,
                      -23.5,
                      city_lon,
                      color='ivory',
                      label="Tropic of\nCapricorn")
        draw_parallel(m, 0, city_lon, color='ivory', label='Equator')

        # mark city
        citydot(m, city_lat, city_lon, 'white')

        # mark sun position
        sundot(m, sun_lat, sun_lon, 'y', label='subsolar')
        draw_parallel(m, sun_lat, city_lon, color='yellow')

        datestring = obs.date.datetime().strftime("%Y-%m-%d")
        frames = 1
        if '6-21' in datestring or '12-21' in datestring or '6-.8020' in datestring:
            datestring += " Solstice"
            frames = 20
        if '3-19' in datestring or '9-23' in datestring:
            datestring += " Equinox"
            frames = 40
        plt.annotate(datestring,
                     xy=(10, 10),
                     fontsize=20,
                     textcoords='data',
                     color='w')
        plt.savefig(filename, transparent=True)
        plt.close()
        from PIL import Image
        fg = Image.open(filename, 'r')
        bg = Image.open('starfield.png', 'r')
        text_img = Image.new('RGBA', (1920, 1080), (0, 0, 0, 0))
        text_img.paste(bg, (0, 0))
        text_img.paste(fg, (0, 0), mask=fg)
        text_img.save(filename, format="png")

        for x in range(1, frames):
            filename2 = "images/%s/plot_%s_%02d.png" % (
                city, obs.date.datetime().strftime("%Y%m%d"), x)
            shutil.copyfile(filename, filename2)
Beispiel #18
0
def geramapa(star, data, title, labelx, nameimg, mapstyle='1', resolution='l', centermap=None, lats=None, erro=None, ring=None, atm=None, clat=None, sitearq='sites.dat', fmt='png', dpi=100, mapsize=None, cpoints=60, off=0):
    lon = star.ra - data.sidereal_time('mean', 'greenwich')
    center_map = EarthLocation(lon.value, star.dec.value)
    fig = plt.figure(figsize=(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value))
    if not centermap == None:
        center_map = EarthLocation(centermap[0],centermap[1])
#    m = Basemap(projection='ortho',lat_0=center_map.latitude.value,lon_0=center_map.longitude.value,resolution=resolution)
    m = Basemap(projection='ortho',lat_0=center_map.latitude.value,lon_0=center_map.longitude.value,resolution=resolution,llcrnrx=-3500000.,llcrnry=-3717000.,urcrnrx=500000.,urcrnry=-413000.)
    kx = fig.add_axes([0.105,0.1,0.894,0.894])
    kx.set_rasterization_zorder(1)
    m.nightshade(data.datetime, alpha=0.3, zorder=0.5)  ## desenha a sombra da noite
    m.drawcoastlines(linewidth=0.5)  ## desenha as linhas da costa
    m.drawcountries(linewidth=0.5)  ## desenha os paises
#    m.drawstates(linewidth=0.5)    ## Desenha os estados
    m.drawmeridians(np.arange(0,360,30))  ## desenha os meridianos
    m.drawparallels(np.arange(-90,90,30))  ## desenha os paralelos
    m.drawmapboundary()  ## desenha o contorno do mapa
    mapsstyle = {'STE' : 'blue', 'JPL' : 'red', '22fev' : 'black', '03mar' : 'green'}
    pontos = {'STE' : '-', 'JPL' : '--', '22fev' : '-.', '03mar' : ':'}
    style = {'1': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'blue', 'rncolor':'blue', 'atcolor':'blue', 'outcolor':'red'},
             '2': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'},
             '3': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'},
             '4': {'ptcolor': 'red', 'lncolor': 'red', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'},
             '5': {'ptcolor': 'red', 'lncolor': 'red', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'}}
    if mapstyle == '2':
        m.drawmapboundary(fill_color='aqua')
        m.fillcontinents(color='coral',lake_color='aqua')
    elif mapstyle == '3':
        m.shadedrelief()
    elif mapstyle == '4':
        m.bluemarble()
    elif mapstyle == '5':
        m.etopo()
    for tipo in ['STE', 'JPL', '22fev', '03mar']:
#    if not lats == None:
        xs, ys = m(lats[tipo][0], lats[tipo][1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
#        m.plot(xs, ys, color=mapsstyle[tipo])
        xt, yt = m(lats[tipo][2], lats[tipo][3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
#        m.plot(xt, yt, color=mapsstyle[tipo])
#        m.plot(lats[tipo][4], lats[tipo][5], color=mapsstyle[tipo], zorder=-0.2)
#        m.plot(lats[tipo][6], lats[tipo][7], color=mapsstyle[tipo], zorder=-0.2)
#    else:
#        m.plot(lats[4], lats[5], color=style[mapstyle]['outcolor'], clip_on=False, zorder=0.2)
#        m.plot(lats[6], lats[7], color=style[mapstyle]['outcolor'], clip_on=False, zorder=0.2)
#    if not erro == None:
#        xs, ys = m(erro[0], erro[1])
#        xs = [i for i in xs if i < 1e+30]
#        ys = [i for i in ys if i < 1e+30]
#        m.plot(xs, ys, '--', color=style[mapstyle]['ercolor'])
#        xt, yt = m(erro[2], erro[3])
#        xt = [i for i in xt if i < 1e+30]
#        yt = [i for i in yt if i < 1e+30]
#        m.plot(xt, yt, '--', color=style[mapstyle]['ercolor'])
#    if not ring == None:
#        xs, ys = m(ring[0], ring[1])
#        xs = [i for i in xs if i < 1e+30]
#        ys = [i for i in ys if i < 1e+30]
#        m.plot(xs, ys, '--', color=style[mapstyle]['rncolor'])
#        xt, yt = m(ring[2], ring[3])
#        xt = [i for i in xt if i < 1e+30]
#        yt = [i for i in yt if i < 1e+30]
#        m.plot(xt, yt, '--', color=style[mapstyle]['rncolor'])
#    if not atm == None:
#        xs, ys = m(atm[0], atm[1])
#        xs = [i for i in xs if i < 1e+30]
#        ys = [i for i in ys if i < 1e+30]
#        m.plot(xs, ys, color=style[mapstyle]['atcolor'])
#        xt, yt = m(atm[2], atm[3])
#        xt = [i for i in xt if i < 1e+30]
#        yt = [i for i in yt if i < 1e+30]
#        m.plot(xt, yt, color=style[mapstyle]['atcolor'])
#    if not clat == None:
        xc, yc, lab = [], [], []
        cp = Time(clat[tipo][5], format='iso')
        vec = np.arange(0, (cp[-1] - data).sec, cpoints)
        vec = np.sort(np.concatenate((vec,-vec[1:]), axis=0))*u.s
#        for i in vec:
#            g = data + TimeDelta(i) + TimeDelta(off*u.s)
#            if g.iso in clat[tipo][2]:
#                a = np.where(np.array(clat[tipo][2]) == g.iso)
#                x, y = m(np.array(clat[tipo][0])[a], np.array(clat[tipo][1])[a])
#                xc.append(x)
#                yc.append(y)
#                lab.append(g.iso.split()[1][0:8])
#            elif g.iso in clat[tipo][5]:
#                a = np.where(np.array(clat[tipo][5]) == g.iso)
#                xc.append(np.array(clat[tipo][3])[a])
#                yc.append(np.array(clat[tipo][4])[a])
#                lab.append(g.iso.split()[1][0:8])
#            else:
#                if len(clat[tipo][2]) == 0:
#                    a = [0]
#                else:
#                    co = Time(clat[tipo][2], format='iso')
#                    a = np.argsort(np.absolute(co - g))[0:2]
#                if 0 not in a and len(co)-1 not in a:
#                    b = np.absolute((co[a] - g).sec)
#                    x, y = m(np.array(clat[tipo][0])[a], np.array(clat[tipo][1])[a])
#                    xc.append(np.sum(x*(1/b))/np.sum(1/b))
#                    yc.append(np.sum(y*(1/b))/np.sum(1/b))
#                    lab.append(g.iso.split()[1][0:8])
#                else:
#                    co = Time(clat[tipo][5], format='iso')
#                    a = np.argsort(np.absolute(co - g))[0:2]
#                    b = np.absolute((co[a] - g).sec)
#                    xc.append(np.sum(np.array(clat[tipo][3])[a]*(1/b))/np.sum(1/b))
#                    yc.append(np.sum(np.array(clat[tipo][4])[a]*(1/b))/np.sum(1/b))
#                    lab.append(g.iso.split()[1][0:8])
        x, y = m(np.array(clat[tipo][0]), np.array(clat[tipo][1]))
        m.plot(x, y, color=mapsstyle[tipo])#, markersize=mapsize[0].value*8/46)
        m.plot(clat[tipo][6][0], clat[tipo][6][1], 'o', color=mapsstyle[tipo], markersize=mapsize[0].value*10/46)#, marker=(2,0,165))
#        print clat[6][0], clat[6][1]

#    for label, axpt, bypt in zip(lab, xc, yc):
#        plt.text(axpt + 0, bypt + 350000, label, rotation=60, weight='bold')

#    m.plot(ax,by, 'o', color=ptcolor, markersize=int(mapsize[0].value*20/46))
#    m.plot(ax2.to(u.m),by2.to(u.m), 'o', color=ptcolor, markersize=int(mapsize[0].value*12/46))
#    m.plot(ax3.to(u.m), by3.to(u.m), color='red')
#    m.plot(ax4.to(u.m), by4.to(u.m), color='red')
#    m.quiver(a-0*u.m,b-600000*u.m, 20, 0, width=0.005)

#    ax2 = a + dista*np.sin(pa) + [(i - datas).sec for i in temposplot]*u.s*vel*np.cos(paplus)
#    by2 = b + dista*np.cos(pa) - [(i - datas).sec for i in temposplot]*u.s*vel*np.sin(paplus)
#
#    labels = [i.iso.split()[1][0:8] for i in temposplot]
#    m.plot(ax2, by2, 'ro')

    if os.path.isfile(sitearq) == True:
        sites = np.loadtxt(sitearq, dtype={'names': ('lat', 'lon', 'alt', 'nome'), 'formats': ('f8', 'f8', 'f8', 'S30')})
        xpt,ypt = m(sites['lon'],sites['lat'])
        m.plot(xpt,ypt,'go')
#        offset = [[xpt[0] + 100000,xpt[0] + 100000,xpt[0] + 100000,xpt[3] + 400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000],[10000,-30000,-60000,70000,30000,-20000,-70000,-30000,-70000]]
#        for i in np.arange(len(xpt)):
#            ax.text(offset[0][i],ypt[i]+offset[1][i],sites['nome'][i], weight='bold')

#    m.plot(ax5.to(u.m), by5.to(u.m), '--', color=dscolor, label='+-{} error'.format(erro))
#    m.plot(ax6.to(u.m), by6.to(u.m), '--', color=dscolor)
#    plt.legend(fontsize=mapsize[0].value*21/46)

#    m.plot(5771363.97687, 4156344.21479, '+', color='black', markersize=mapsize[0].value*20/46)
#5771363.97687 4156344.21479

#    fig = plt.gcf()
#    fig.set_size_inches(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value)
#    plt.title(title, fontsize=mapsize[0].value*25/46, fontproperties='FreeMono', weight='bold')
#    plt.xlabel(labelx, fontsize=mapsize[0].value*21/46, fontproperties='FreeMono', weight='bold')
#    e,w = m(center_map.longitude.value,center_map.latitude.value)
    e, w = clat['STE'][6][0], clat['STE'][6][1]
    
    plt.errorbar(e - 50000, w + 1250000, yerr=75000, color='black')
    plt.errorbar(e - 50000, w + 1000000, yerr=98000, color='black')
    plt.text(e, w + 1225000, 'Himalia Diameter (150 km)', fontsize=sizel)
    plt.text(e, w + 975000, 'Estimated Error (60 mas)', fontsize=sizel)
    
    plt.xscale(u'linear')
    plt.xticks(np.arange(-2500000, 1500000, 500000) + e, np.arange(-2.5, 1.5, 0.5), fontsize=sizel)
    plt.xlabel(r'$\times 10^{3}$(km)', fontsize=sizel)
    plt.yscale(u'linear')
    plt.yticks(np.arange(-1500000, 2000000, 500000) + w, np.arange(-1.5, 2.0, 0.5), fontsize=sizel)#, rotation=90)
    plt.ylabel(r'$\times 10^{3}$(km)', fontsize=sizel)
    plt.savefig('HIMALIA.{}'.format(fmt), format=fmt, dpi=dpi, bbox_inches='tight')
    print 'Gerado: HIMALIA.{}'.format(fmt)
    plt.clf()
class ISSData():
    Arrays = []
    rows = 0
    n = 0
    step = 1104
    Headers = []
    Directory = ''
    normPath = ""
    chatty = False
    map = ""
    ag = ""

    def __init__(self, fileName, directory=""):
        """ Check to see if files exists 
      """
        self.map = Basemap(projection='mill', lon_0=-10)
        normPath = os.path.normpath(directory + fileName)
        try:
            dFile = open(normPath, "r")
        except:
            print "Cannot open", normPath
        # save tested path for later use
        self.normPath = normPath
        dFile.close()

    def readDataFromFile(self):
        NL = 0
        with open(self.normPath) as file:
            for line in file:
                line = line.rstrip()
                NL += 1
                ns = line.split(",")
                if (NL == 1):
                    headers = ns
                    for h in headers:
                        self.Headers.append(h)
                    self.Headers.pop(
                        -1)  # remove time stamp header as time is not a float
                    for val in ns:
                        empty = []
                        self.Arrays.append(empty)
                else:
                    nv = 0
                    for val in ns:
                        self.Arrays[nv].append(val)
                        nv += 1
        file.close()
        self.rows = len(self.Arrays[0])

        nh = 0
        print " File", self.normPath, "  rows=", self.rows, self.rows / 360, "hours"
        print self.Arrays[19][0], " - ", self.Arrays[19][-1]
        print " Measurement      #    min         max        median      average    stddev"
        for h in self.Headers:
            narray = np.array(self.Arrays[nh]).astype(np.float32)
            if (nh == 0):
                # each data point is 10 secs so this scales x axis to minutes
                narray = narray / 6.0
            #Calculate some basic stats on each row

            max = np.amax(narray)
            if (headers[nh] == "pitch") or (headers[nh] == "yaw"):
                if (max >= 20000.):
                    # convert from radians to degrees?
                    # in the first Spacecraft dataset only (I think)
                    narray = narray / 57.3
                nv = 0
                for val in narray:
                    if (val <= -180.0):
                        narray[nv] = narray[nv] + 360.0
                    elif (val >= 180.0):
                        narray[nv] = narray[nv] - 360.0
                    nv += 1
                    # pitch looks better when normalized about zero
                max = np.amax(narray)
            min = np.amin(narray)
            med = np.median(narray)
            aver = np.average(narray)
            stddev = np.std(narray)
            print "%12s %6s %10.5f %10.5f %10.5f %10.5f %10.5f" % (
                h, nh, min, max, med, aver, stddev)
            self.Arrays[nh] = narray
            nh += 1
        # Normalize

    def printStats(self, param=1, n=0, step=1104):
        print step,"datapoints - ", (self.Arrays[19][n])," - ", \
        (self.Arrays[19][n+step])
        print " Measurement      #    min         max        median      average    stddev"
        min = np.amin(self.Arrays[param][n:n + step])
        max = np.amax(self.Arrays[param][n:n + step])
        med = np.median(self.Arrays[param][n:n + step])
        aver = np.average(self.Arrays[param][n:n + step])
        stddev = np.std(self.Arrays[param][n:n + step])
        print "%12s %6s %10.5f %10.5f %10.5f %10.5f %10.5f" % (
            self.Headers[param], param, min, max, med, aver, stddev)

    def drawNightDay(self, param=1, n=0, step=1104):
        if (self.chatty): print self.Headers[param], n, step
        cn = int(n + step / 2)
        ct = self.Arrays[19][cn]
        print "Centre time period = ", ct
        # miller projection

        # plot coastlines, draw label meridians and parallels.
        self.map.drawcoastlines()
        self.map.drawparallels(np.arange(-90, 90, 30), labels=[1, 0, 0, 0])
        self.map.drawmeridians(np.arange(self.map.lonmin, self.map.lonmax + 30,
                                         60),
                               labels=[0, 0, 0, 1])
        # fill continents 'coral' (with zorder=0), color wet areas 'aqua'
        self.map.drawmapboundary(fill_color='white')
        self.map.fillcontinents(color='coral', lake_color='white')
        # shade the night areas, with alpha transparency so the
        # map shows through. Use current time in UTC.
        #en = el.findIndexFromDate(ct)
        #eo = el.extractISSfromIndex(en)
        #print eo
        date = el.findDateFromString(ct)
        if (step <= 1104):
            self.map.nightshade(date)
        else:
            print "Track too long for night shading"
        plt.title('ISS Track %s (UTC)' % ct)
#        self.drawIssTrack(elements,param,n,step)

    def drawIssTrack(self, elements, param=1, n=0, step=1104):
        st = self.Arrays[19][n]
        et = self.Arrays[19][n + step]
        print "Plotting from - ", st, " to ", et
        cn = int(n + step / 2)
        ct = self.Arrays[19][cn]
        line1, line2 = elements.elemsFromDateString(ct)
        if (self.chatty): print "drawIssTrack", n, step, ct, line1, line2
        for nn in range(n, n + step, 6):
            ntime = self.Arrays[19][nn]
            #if self.chatty: print ntime
            tle_rec = ephem.readtle("ISS", line1, line2)
            tle_rec.compute(ntime)
            #convert to strings#
            lat2string = str(tle_rec.sublat)
            long2string = str(tle_rec.sublong)
            lati = lat2string.split(":")
            longt = long2string.split(":")
            #if self.chatty: print "ISS SUBSURFACE -", lati,longt
            lat = float(
                lati[0]) + float(lati[1]) / 60. + float(lati[2]) / 3600.
            lon = float(
                longt[0]) + float(longt[1]) / 60. + float(longt[2]) / 3600.
            xpt, ypt = self.map(lon, lat)
            # drawing style
            kargs = "g+"
            if (nn == n):
                plt.text(xpt, ypt, "start")
            if (nn >= (n + step - 6)):
                plt.text(xpt, ypt, "end")

# make every 5 mins dot
            if ((nn % 30) == 0): kargs = "g."
            self.map.plot(xpt, ypt, kargs)

    def drawDataPlot(self, param=1, n=0, step=1104):
        plt.figure(1)
        plt.clf()
        plt.title(self.Headers[param])
        plt.plot(self.Arrays[0][n:(n + step)],
                 self.Arrays[param][n:(n + step)])
        #self.ag.set_xdata(self.Arrays[0][n:(n+step)])
        plt.draw()
Beispiel #20
0
a, b = map(-30, -15)
plt.text(a, b, timestr, fontsize='xx-small',
         color='white')  ##########TIMESTAMP FOR MAP >>ATLANTIC<<
plt.text(a - 120, b, timestr, fontsize='xx-small',
         color='white')  ##########TIMESTAMP FOR MAP >>Pacific<<
plt.text(a + 118, b, timestr, fontsize='xx-small',
         color='white')  ##########TIMESTAMP FOR MAP >>INDIAN<<

m, n = map(-20, -20)
#img = mpimg.imread('/shared/sos/json/legend.png')
#m.imshow(img, extent=(m,m-10,n,n-20)

log = open("/shared/sos/json/logs/AVedge.txt", "a")
log.writelines("GENERATED----MAP ----" + timestr + "\n")
#x, y = map(40.8228,47.9151)
#plt.plot(x, y, marker='D',color='yellow',markersize=1)

date = datetime.utcnow()
CS = map.nightshade(date)

#plt.title('Day/Night Map for %s (UTC)' %strftime("%d %b %Y %H:%M:%S"))
#plt.show()
plt.savefig('/shared/sos/json/dataset/' + timestr + ".png",
            bbox_inches='tight',
            pad_inches=-0.037,
            dpi=200)
plt.savefig("/shared/sos/json/dataset/flights.png",
            bbox_inches='tight',
            pad_inches=-0.037,
            dpi=200)
Beispiel #21
0
def combined_all_ghgs(sim_file, lattice_files, datetime, centre, xco2_lims=None, xco_lims=None, xch4_lims=None, map_bkgd='bluemarble', cmap='jet', out='show', **kwargs):

    fig = plt.figure(figsize=(15,12))
    
    xco2_ax = fig.add_subplot(231)
    xco_ax = fig.add_subplot(232)
    xch4_ax = fig.add_subplot(233)
    cld_ax = fig.add_subplot(223)
    ret_ax = fig.add_subplot(224)
    
    
    #####################################
    
    plt.sca(xco2_ax)
    
    
    xco2, xco2_lats, xco2_lons = ec_cas.global_XCO2(datetime)
    
    proj_xco2 = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='l')
    
    proj_xco2.drawcoastlines(linewidth=0.75)
    proj_xco2.drawcountries(linewidth=0.5)
    proj_xco2.drawmeridians(np.arange(-180, 181, 30), latmax=90, linewidth=0.5)
    proj_xco2.drawparallels(np.arange(-90, 91, 15), latmax=90, linewidth=0.5)
    
    
    lon, lat = np.meshgrid(xco2_lons, xco2_lats)
    x,y = proj_xco2(lon, lat)
    
    xco2_mask = np.ma.masked_greater(x, 1e15).mask
    xco2_masked = np.ma.array(xco2, mask=xco2_mask)
    
    if xco2_lims:
        vmin_xco2, vmax_xco2 = xco2_lims
    else:
        vmin_xco2 = xco2_masked.min() // 1.
        vmax_xco2 = xco2_masked.max() // 1. + 1.
    
    sm_xco2 = ScalarMappable(Normalize(vmin=vmin_xco2, vmax=vmax_xco2), cmap=cmap)
    levs_xco2 = np.linspace(vmin_xco2, vmax_xco2, 256)
    clevs_xco2 = [sm_xco2.to_rgba(lev) for lev in levs_xco2]
    
    xco2_ctr = plt.contourf(x, y, xco2_masked, levs_xco2, colors=clevs_xco2, extend='both')
    
    xco2_cbar = plt.colorbar(xco2_ctr, orientation='vertical', fraction=0.05, aspect=40, shrink=0.75)
    xco2_cbar.set_label('XCO$_2$ [ppm]')
    xco2_cbar.set_ticks(np.arange(vmin_xco2, vmax_xco2+0.25, 0.5))
    
    plt.title(datetime.strftime('XCO$_2$ %d %b %Y %H:%M:%S'))
    
    
    ######################################
    
    plt.sca(xco_ax)
    
    xco, xch4, xlats, xlons = ec_cas.global_ghg(datetime)
    
    proj_xco = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='l')
    
    proj_xco.drawcoastlines(linewidth=0.75)
    proj_xco.drawcountries(linewidth=0.5)
    proj_xco.drawmeridians(np.arange(-180, 181, 30), latmax=90, linewidth=0.5)
    proj_xco.drawparallels(np.arange(-90, 91, 15), latmax=90, linewidth=0.5)
    
    
    lon, lat = np.meshgrid(xlons, xlats)
    x,y = proj_xco(lon, lat)
    
    xco_mask = np.ma.masked_greater(x, 1e15).mask
    xco_masked = np.ma.array(xco, mask=xco_mask)
    
    if xco_lims:
        vmin_xco, vmax_xco = xco_lims
    else:
        vmin_xco = xco_masked.min() // 1.
        vmax_xco = xco_masked.max() // 1. + 1.
    
    sm_xco = ScalarMappable(Normalize(vmin=vmin_xco, vmax=vmax_xco), cmap=cmap)
    levs_xco = np.linspace(vmin_xco, vmax_xco, 256)
    clevs_xco = [sm_xco.to_rgba(lev) for lev in levs_xco]
    
    xco_ctr = plt.contourf(x, y, xco_masked, levs_xco, colors=clevs_xco, extend='both')
    
    xco_cbar = plt.colorbar(xco_ctr, orientation='vertical', fraction=0.1, aspect=40, shrink=0.75)
    xco_cbar.set_label('XCO [ppb]')
    xco_cbar.set_ticks(np.int64(np.arange(vmin_xco, vmax_xco+1, 10)))
    
    plt.title(datetime.strftime('XCO %d %b %Y %H:%M:%S'))
    
    
    #######################################
    
    plt.sca(xch4_ax)
    
    proj_xch4 = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='l')
    
    proj_xch4.drawcoastlines(linewidth=0.75)
    proj_xch4.drawcountries(linewidth=0.5)
    proj_xch4.drawmeridians(np.arange(-180, 181, 30), latmax=90, linewidth=0.5)
    proj_xch4.drawparallels(np.arange(-90, 91, 15), latmax=90, linewidth=0.5)
    
    
    lon, lat = np.meshgrid(xlons, xlats)
    x,y = proj_xch4(lon, lat)
    
    xch4_mask = np.ma.masked_greater(x, 1e15).mask
    xch4_masked = np.ma.array(xch4, mask=xch4_mask)
    
    if xch4_lims:
        vmin_xch4, vmax_xch4 = xch4_lims
    else:
        vmin_xch4 = xch4_masked.min() // 1.
        vmax_xch4 = xch4_masked.max() // 1. + 1.
    
    sm_xch4 = ScalarMappable(Normalize(vmin=vmin_xch4, vmax=vmax_xch4), cmap=cmap)
    levs_xch4 = np.linspace(vmin_xch4, vmax_xch4, 256)
    clevs_xch4 = [sm_xch4.to_rgba(lev) for lev in levs_xch4]
    
    xch4_ctr = plt.contourf(x, y, xch4_masked, levs_xch4, colors=clevs_xch4, extend='both')
    
    xch4_cbar = plt.colorbar(xch4_ctr, orientation='vertical', fraction=0.1, aspect=40, shrink=0.75)
    xch4_cbar.set_label('XCH$_4$ [ppb]')
    xch4_cbar.set_ticks(np.int64(np.arange(vmin_xch4, vmax_xch4 + 1, 20)))
    
    plt.title(datetime.strftime('XCH$_4$ %d %b %Y %H:%M:%S'))
    
    
    ##############################################################
    
    plt.sca(cld_ax)
    
    
    mission = retrievals.Mission(sim_file, *lattice_files, **kwargs)
    
    obs_time = time_utils.Time(datetime, mission.satellite.times[0].ref)        
        
    # find the closest apogee point to obs_time
    apogees = mission.satellite.get_apogees()
    apogee_ind = time_utils.closest_index(obs_time, apogees)
    
    # create the ObservationPeriod instance, and generate the Retrieval instances
    obs = retrievals.ObservationPeriod(mission, apogees[apogee_ind], mission.lattice_files[apogee_ind%2])
    obs.main_filter()
    obs.generate_retrievals()
    
    # find the closest segment of the observation period
    obs_ind = time_utils.closest_index(obs_time, obs.obs_middle)
    
    clat, clon = centre
    proj_cld = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='c')
    
    # draw cloud data that was used to determine FOV locations
    obs.cloud_collection.show_clouds_ortho(obs.cloud_times[obs_ind], centre, map_bkgd=map_bkgd, out='')
    
    proj_cld.nightshade(datetime)
    
    # draw a red border around each of the selected FOVs
    for ret in obs.retrievals[obs_ind]:
        
        lats = np.concatenate([ret.pixel_lats[:,0], ret.pixel_lats[-1,:], ret.pixel_lats[::-1,-1], ret.pixel_lats[0,::-1]])
        lons = np.concatenate([ret.pixel_lons[:,0], ret.pixel_lons[-1,:], ret.pixel_lons[::-1,-1], ret.pixel_lons[0,::-1]])
        
        x,y = proj_cld(lons, lats)
        coords = np.vstack([x,y]).T
        
        if not np.sum(coords > 1e15):
        
            p = Polygon(coords, fill=False, edgecolor='r', zorder=10)
            plt.gca().add_patch(p)
        
    plt.title('FoV Selections {0} - {1} UTC'.format(obs.obs_times[obs_ind].strf('%d %B %Y %H:%M'), obs.obs_times[obs_ind+1].strf('%H:%M')))
    
    
    ##############################################################
    
    plt.sca(ret_ax)
    
    
    proj_ret = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='l')
    
    if map_bkgd == 'bluemarble':
        proj_ret.bluemarble()
    elif map_bkgd == 'etopo':
        proj_ret.etopo()
    elif map_bkgd == 'mask':
        proj_ret.drawlsmask(land_color='limegreen', ocean_color='dodgerblue', resolution='l')
        
        proj_ret.drawcoastlines(linewidth=0.75)
        proj_ret.drawcountries(linewidth=0.5)
        proj_ret.drawmeridians(np.arange(-180, 181, 30), latmax=90, linewidth=0.5)
        proj_ret.drawparallels(np.arange(-90, 91, 15), latmax=90, linewidth=0.5)
    else:
        raise ValueError('invalid map background specification')
    
    proj_ret.nightshade(datetime)
    
    
    
    for ret in obs.retrievals[obs_ind]:
                
        x,y = proj_ret(ret.pixel_lons, ret.pixel_lats)
                
        if not np.sum(x > 1e15):
        
            
            ret_mask = ret.valid_retrievals == 0
            ret_masked = np.ma.array(np.ones(ret.pixel_lats.shape), mask=ret_mask)
            
            ret_ctr = plt.contourf(x, y, ret_masked, [0,1], colors=['red'], extend='both')
        
    
    plt.title('AIM-North Retrievals {0} - {1} UTC'.format(obs.obs_times[obs_ind].strf('%d %B %Y %H:%M'), obs.obs_times[obs_ind+1].strf('%H:%M')))   
            
    ##############################################################
    
    plt.subplots_adjust(left=0.01, right=0.95, bottom=0.025, top = 0.975, wspace=0.175, hspace=0.1)
    
    if out == 'show':
        plt.show()
    elif out == '':
        pass
    else:
        plt.savefig(os.path.join('../figures/combined_plots/', out))
        plt.close()
def plot_burst_map(sub_axis, gps_data, burst, 
        show_terminator = True, plot_trajectory=True, show_transmitters=True,
        TLE_file = 'resources/VPM_TLEs.json', TX_file='resources/nb_transmitters.conf'):

    logger = logging.getLogger()

    #m_ax = fig.add_subplot(1,1,1)
    m_ax = sub_axis

    m = Basemap(projection='mill',lon_0=0,ax=m_ax, llcrnrlon=-180,llcrnrlat=-70,urcrnrlon=180,urcrnrlat=70)

    lats = [x['lat'] for x in gps_data]
    lons = [x['lon'] for x in gps_data]
    T_gps = [x['timestamp'] for x in gps_data]

    # still trying to fix this
    #for ti, tt in enumerate(T_gps):
    #    if datetime.datetime.utcfromtimestamp(tt).year == 1980:
    #        T_gps.pop(ti)
    #        lats.pop(ti)
    #        lons.pop(ti)

    T_gps = np.array(T_gps)

    sx,sy = m(lons, lats)

    m.drawcoastlines(color='k',linewidth=1,ax=m_ax);
    m.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0]);
    m.drawmeridians(np.arange(m.lonmin,m.lonmax+30,60),labels=[0,0,1,0]);
    m.drawmapboundary(fill_color='cyan');
    m.fillcontinents(color='white',lake_color='cyan');


    #check_lat = [x['lat'] for x in gps_data]
    #check_lon = [x['lon'] for x in gps_data]

    #if check_lat[0] == 0 and check_lon[0] == 0:
    #    TLE_lib = load_TLE_library(TLE_file)

    # quick fix for missing gps
    start_timestamp = datetime.datetime.utcfromtimestamp(burst['header_timestamp'])
    avg_ts = float(burst['header_timestamp']) + 10

    if show_terminator:
        try:
            # Find the median timestamp to use:
            #avg_ts = np.mean([k['timestamp'] for k in gps_data if k['time_status'] > 19])

            CS=m.nightshade(datetime.datetime.utcfromtimestamp(avg_ts))
        except:
            logger.warning('Problem plotting day/night terminator')

    if plot_trajectory:
        try:
            # (Here's the old method, where you pass a TLE to it as text)
            # if TLE_file:
            #     try:
            #         with open(TLE_file,'r') as file:
            #             TLE = file.read().split('\n')
            #             logger.info(
            #                 f'loaded TLE file {TLE_file}')
            #     except:
            #         logger.warning(f'failed to load TLE file {TLE_file}')
            # else:
            #     logger.info('using default TLE')
            #     # A default TLE, from mid-may 2020.
            #     TLE = ["1 45120U 19071K   20153.15274580 +.00003602 +00000-0 +11934-3 0  9995",
            #            "2 45120 051.6427 081.8638 0012101 357.8092 002.2835 15.33909680018511"]

            # 10-27-2020: This version to find the closest TLE in the JSON file
            # You can change the length of the ground track plot by changing t1, t2, and tvec
            TLE_lib = load_TLE_library(TLE_file)

            #avg_ts = np.mean([k['timestamp'] for k in gps_data if k['time_status'] > 19])
            
            t_mid = datetime.datetime.utcfromtimestamp(avg_ts)

            t1 = t_mid - datetime.timedelta(minutes=15)
            t2 = t_mid + datetime.timedelta(minutes=15)

            #traj, tvec = compute_ground_track(TLE, t1, t2, tstep=datetime.timedelta(seconds=10))
            tvec = [(t1 + datetime.timedelta(seconds=int(x))) for x in np.arange(0,30*60, 10)]
            simtime = [x.replace(tzinfo=datetime.timezone.utc).timestamp() for x in tvec]

            traj,_ = get_position_from_TLE_library(simtime, TLE_lib)

            tlats = traj[:,1]
            tlons = traj[:,0]

            mid_ind = np.argmin(np.abs(np.array(tvec) - t_mid))
            zx,zy = m(tlons, tlats)
            z = m.scatter(zx,zy,c=simtime, marker='.', s=10, alpha=0.5, cmap = get_cmap('plasma'), zorder=100, label='TLE')

            z2 =m.scatter(zx[mid_ind], zy[mid_ind],edgecolor='k', marker='*',s=50, zorder=101, label='Center (TLE)')
        except:
            logger.warning('Problem plotting ground track from TLE')

    if show_transmitters:
        try:
            call_sign_config = ConfigParser()
            try:
                fp = open(TX_file)
                call_sign_config.read_file(fp)
                fp.close()
            except:
                logger.warning('failed to load transmitters file')

            for tx_name, vals in call_sign_config.items('NB_Transmitters'):
                vv = vals.split(',')
                tx_freq = float(vv[0])
                tx_lat  = float(vv[1])
                tx_lon  = float(vv[2])
                px,py = m(tx_lon, tx_lat)
                p = m.scatter(px,py, marker='p', s=20, color='r',zorder=99)
                name_str = '{:s}  \n{:0.1f}  '.format(tx_name.upper(), tx_freq/1000)
                m_ax.text(px, py, name_str, fontsize=8, fontweight='bold', ha='left',
                    va='bottom', color='k', label='TX')
            p.set_label('TX')
            s = m.scatter(sx,sy,c=T_gps, marker='o', s=20, cmap = get_cmap('plasma'), zorder=100, label='GPS')
        except:
            logger.warning('Problem plotting narrowband transmitters')
    m_ax.legend(bbox_to_anchor=(1.05,1), loc='upper left', ncol=2)

    gstr = ''
    for entry in gps_data:
        print('hey',entry)
        time = datetime.datetime.strftime(datetime.datetime.utcfromtimestamp(entry['timestamp']),'%D %H:%M:%S')
        tloc = entry['time_status'] > 20
        ploc = entry['solution_status'] ==0
        if time[6:8] == '20': # don't include the 1980 ones
            gstr+= '{:s} ({:1.2f}, {:1.2f}):\ntime lock: {:b} position lock: {:b}\n'.format(time, entry['lat'], entry['lon'], tloc,ploc)
    time = datetime.datetime.strftime(datetime.datetime.utcfromtimestamp(burst['header_timestamp']),'%D %H:%M:%S')
    gstr = '{:s}'.format(time) + ' (' + str(round(tlats[len(tlats)//2],2)) + ', ' + str(round(tlons[len(tlons)//2],2)) + ') \n TLE generated'
    gstr = '06/14/20 06:59:20 (-43.64, -120.91): \ntime lock: 1 position lock: 1 \n06/14/20 06:59:32 (-44.03, -120.06): \ntime lock: 1 position lock: 1 \n06/14/20 06:59:44 (-44.41, -119.19): \ntime lock: 1 position lock: 1 \n06/14/20 06:59:56 (-44.79, -118.31): \ntime lock: 1 position lock: 1 \n06/14/20 07:00:08 (-45.16, -117.42): \ntime lock: 1 position lock: 1 \n'
    
    #m_ax.text(1, 0, gstr, fontsize='10') # ha='center', va='bottom')    
    return gstr
Beispiel #23
0
def bluemarble_daynight1(date, lon, lat, scale):

    # Define Bluemarble and Nightshade objects
    fig, axes = plt.subplots(1, figsize=(16, 16))
    m = Basemap(projection='ortho',
                resolution=None,
                lat_0=lat[0],
                lon_0=lon[0],
                area_thresh=None,
                ax=axes)
    bm = m.bluemarble(scale=scale)
    ns = m.nightshade(date, alpha=0.5)

    bm_rgb = bm.get_array()
    bm_ext = bm.get_extent()

    axes.cla()

    # Get the x and y index spacing
    x = np.linspace(bm_ext[0], bm_ext[1], bm_rgb.shape[1])
    y = np.linspace(bm_ext[2], bm_ext[3], bm_rgb.shape[0])

    # Define coordinates of the Bluemarble image
    x3d, y3d = np.meshgrid(x, y)
    pts = np.hstack((x3d.flatten()[:, np.newaxis], y3d.flatten()[:,
                                                                 np.newaxis]))

    # Find which coordinates fall in Nightshade
    # The following could be tidied up as there should only ever one polygon. Although
    # the length of ns.collections is 3? I'm sure there's a better way to do this.
    paths, polygons = [], []
    for i, polygons in enumerate(ns.collections):
        for j, paths in enumerate(polygons.get_paths()):
            #print j, i
            msk = paths.contains_points(pts)

    # Redefine mask
    msk = np.reshape(msk, bm_rgb[:, :, 0].shape)
    msk_s = np.zeros(msk.shape)
    msk_s[~msk] = 1.

    # Smooth interface between Night and Day
    for s in range(
            int(bm_rgb.shape[1] / 50)
    ):  # Make smoothing between day and night a function of Bluemarble resolution
        msk_s = 0.25 * (  np.vstack( (msk_s[-1,:            ], msk_s[:-1, :            ]) )  \
                        + np.vstack( (msk_s[1:,:            ], msk_s[0  , :            ]) )  \
                        + np.hstack( (msk_s[: ,0, np.newaxis], msk_s[:  , :-1          ]) )  \
                        + np.hstack( (msk_s[: ,1:           ], msk_s[:  , -1,np.newaxis]) ) )

    # Define new RGBA array
    bm_rgba = np.dstack((bm_rgb[:, :, 0:3], msk_s))
    # Plot up Bluemarble Nightshade
    m = Basemap(projection='ortho',
                resolution=None,
                lat_0=lat[0],
                lon_0=lon[0],
                area_thresh=None,
                ax=axes)
    bm_n = m.warpimage('./earth_lights_lrg.jpg', scale=scale)
    #from https://eoimages.gsfc.nasa.gov/images/imagerecords/55000/55167/earth_lights_lrg.jpg
    bm_d = m.imshow(bm_rgba)
    x, y = m(lon[0], lat[0])
    plt.plot(x, y, 'or', markersize=10)
    plt.title('Day/Night Map for %s (UTC)' %
              date.strftime("%d %b %Y %H:%M:%S"),
              fontsize=20)
    plt.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02)
    plt.savefig('output/fig/0/f1.jpg')

    size = np.size(lon)
    xy = np.zeros([size, 2])
    for i in range(size):
        x, y = m(lon[i], lat[i])
        xy[i, 0] = x
        xy[i, 1] = y
    print(xy)
    np.savetxt('output/fig/0/positionxy.dat', xy)
Beispiel #24
0
def geramapa():
    lon = stars.ra - datas.sidereal_time('mean', 'greenwich')
    fig = plt.figure(figsize=(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value))
    m = Basemap(projection='ortho',lat_0=stars.dec.value,lon_0=lon.value,resolution=resolution,llcrnrx=-1800000.,llcrnry=-1200000.,urcrnrx=2200000.,urcrnry=1800000., area_thresh=2000)
#    m = Basemap(projection='ortho',lat_0=stars.dec.value,lon_0=lon.value,resolution=resolution,llcrnrx=-800000.,llcrnry=-450000.,urcrnrx=1200000.,urcrnry=1050000., area_thresh=2000)
    axf = fig.add_axes([-0.001,-0.001,1.002,1.002])
    axf.set_rasterization_zorder(1)
#    m = Basemap(projection='ortho',lat_0=stars.dec.value,lon_0=lon.value,resolution=resolution, llcrnrx=-7000000,llcrnry=-7000000,urcrnrx=7000000,urcrnry=7000000)
    m.drawcoastlines(linewidth=0.5)
    m.drawcountries(linewidth=0.5)
#    m.drawstates(linewidth=0.5)
    m.drawmeridians(np.arange(0,360,30))
    m.drawparallels(np.arange(-90,90,30))
    m.drawmapboundary()
    ptcolor = 'red'
    lncolor = 'black'
    dscolor = 'black'
    if mapstyle == '2':
        m.drawmapboundary(fill_color='aqua')
        m.fillcontinents(color='coral',lake_color='aqua')
        ptcolor = 'red'
        lncolor = 'blue'
        dscolor = 'red'
    elif mapstyle == '3':
        m.shadedrelief()
        ptcolor = 'red'
        lncolor = 'blue'
        dscolor = 'red'
    elif mapstyle == '4':
        m.bluemarble()
        ptcolor = 'red'
        lncolor = 'red'
        dscolor = 'red'
    elif mapstyle == '5':
        m.etopo()
        ptcolor = 'red'
        lncolor = 'red'
        dscolor = 'red'
    if os.path.isfile(sitearq) == True:
        xpt,ypt = m(sites['lon'],sites['lat'])
        m.plot(xpt,ypt,'bo')
        for i in np.arange(len(xpt)):
            plt.text(xpt[i]+50000,ypt[i]-5000,sites['nome'][i])
    CS=m.nightshade(datas.datetime, alpha=0.2, zorder=0.5)
    a, b =m(lon.value, stars.dec.value)
    a = a*u.m
    b = b*u.m
    dista = (dist.to(u.km)*ca.to(u.rad)).value*u.km
    disterr = (dist.to(u.km)*erro.to(u.rad)).value*u.km
    vec = np.arange(0,7000,(np.absolute(vel)*(60*u.s)).value)*u.km + np.absolute(vel)*(60*u.s)
    vec = np.concatenate((vec.value,-vec.value), axis=0)*u.km
    ax = a + dista*np.sin(pa)
    ax2 = ax + vec*np.cos(pa)
    ax3 = ax2 - tamanho/2*np.sin(pa)
    ax4 = ax2 + tamanho/2*np.sin(pa)
    ax5 = a + (dista-disterr)*np.sin(pa) + vec*np.cos(pa)
    ax6 = a + (dista+disterr)*np.sin(pa) + vec*np.cos(pa)
    by = b + dista*np.cos(pa)
    by2 = by - vec*np.sin(pa)
    by3 = by2 - tamanho/2*np.cos(pa)
    by4 = by2 + tamanho/2*np.cos(pa)
    by5 = b + (dista-disterr)*np.cos(pa) - vec*np.sin(pa)
    by6 = b + (dista+disterr)*np.cos(pa) - vec*np.sin(pa)
    m.plot(ax,by, 'o', color=ptcolor, markersize=mapsize[0].value*20/46)
    m.plot(ax2.to(u.m),by2.to(u.m), 'o', color=ptcolor, markersize=mapsize[0].value*10/46)
    m.plot(ax3.to(u.m), by3.to(u.m), color=lncolor)
    m.plot(ax4.to(u.m), by4.to(u.m), color=lncolor)
    m.quiver(ax+800000*u.m,by-1000000*u.m, 10*np.cos(pa),-10*np.sin(pa), width=0.005)

#    ax2 = a + dista*np.sin(pa) + [(i - datas).sec for i in temposplot]*u.s*vel*np.cos(paplus)
#    by2 = b + dista*np.cos(pa) - [(i - datas).sec for i in temposplot]*u.s*vel*np.sin(paplus)

#    labels = [i.iso.split()[1][0:8] for i in temposplot]
#    m.plot(ax2, by2, 'ro')
    
#    for label, axpt, bypt in zip(labels, ax2.value, by2.value):
#        plt.text(axpt + 30000, bypt + 250000, label, rotation=60, weight='bold')

#    if os.path.isfile(sitearq) == True:
#        xpt,ypt = m(sites['lon'],sites['lat'])
#        m.plot(xpt,ypt,'bo')
#        for i in np.arange(len(xpt)):
#            plt.text(xpt[i]+50000,ypt[i]+15000,sites['nome'][i])

#    m.plot(ax5.to(u.m), by5.to(u.m), '--', color=dscolor, label='+-{} error'.format(erro))
#    m.plot(ax6.to(u.m), by6.to(u.m), '--', color=dscolor)
#    plt.legend(fontsize=mapsize[0].value*21/46)

    fig = plt.gcf()
    fig.set_size_inches(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value)
#    plt.title('Objeto       Diam   dots <>  ra_off_obj_de  ra_of_star_de\n{:10s} {:4.0f} km  60 s <> {:+6.1f} {:+6.1f}  {:+6.1f} {:+6.1f} \n'
#        .format(obj, tamanho.value, ob_off_ra.value, ob_off_de.value, st_off_ra.value, st_off_de.value), fontsize=mapsize[0].value*25/46, fontproperties='FreeMono', weight='bold')
#    plt.xlabel('\n year-m-d    h:m:s UT     ra__dec__J2000__candidate    C/A    P/A    vel   Delta   R*   K*  long\n\
#{}  {:02d} {:02d} {:07.4f} {:+02d} {:02d} {:06.3f} {:6.3f} {:6.2f} {:6.2f}  {:5.2f} {:5.1f} {:4.1f}  {:3.0f}'
#        .format(datas.iso, int(stars.ra.hms.h), int(stars.ra.hms.m), stars.ra.hms.s, int(stars.dec.dms.d), np.absolute(int(stars.dec.dms.m)), np.absolute(stars.dec.dms.s),
#        ca.value, pa.value, vel.value, dist.value, magR, magK, longi), fontsize=mapsize[0].value*21/46, fontproperties='FreeMono', weight='bold')
#    plt.savefig('{}_{}.eps'.format(obj, datas.isot),dpi=300, format='eps')
    plt.savefig('{}_{}.eps'.format(obj, datas.isot), format='eps', dpi=300)
    print 'Gerado: {}_{}.eps'.format(obj, datas.isot)
    plt.clf()
Beispiel #25
0
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from datetime import datetime

map = Basemap(projection="vandg", lon_0=0, resolution="c")

map.drawmapboundary(fill_color="#7777ff")
map.fillcontinents(color="#ddaa66", lake_color="#7777ff")

map.drawcoastlines()

map.nightshade(datetime.now(), delta=0.2)

plt.show()
Beispiel #26
0
def combined(sim_file, lattice_files, datetime, centre, xco2_lims=None, map_bkgd='bluemarble', cmap='jet', out='show', **kwargs):
    """
    Create a combined plot 
    """

    _, (xco2_ax, cld_ax, ret_ax) = plt.subplots(nrows=1, ncols=3, figsize=(15,8))
    
    
    ##############################################################
    
    plt.sca(xco2_ax)
    
    
    xco2, xco2_lats, xco2_lons = ec_cas.global_XCO2(datetime)
    
    proj_xco2 = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='l')
    
    proj_xco2.drawcoastlines(linewidth=0.75)
    proj_xco2.drawcountries(linewidth=0.5)
    proj_xco2.drawmeridians(np.arange(-180, 181, 30), latmax=90, linewidth=0.5)
    proj_xco2.drawparallels(np.arange(-90, 91, 15), latmax=90, linewidth=0.5)
    
    
    lon, lat = np.meshgrid(xco2_lons, xco2_lats)
    x,y = proj_xco2(lon, lat)
    
    xco2_mask = np.ma.masked_greater(x, 1e15).mask
    xco2_masked = np.ma.array(xco2, mask=xco2_mask)
    
    if xco2_lims:
        vmin_xco2, vmax_xco2 = xco2_lims
    else:
        vmin_xco2 = xco2.min() // 1.
        vmax_xco2 = xco2.max() // 1. + 1.
    
    sm_xco2 = ScalarMappable(Normalize(vmin=vmin_xco2, vmax=vmax_xco2), cmap=cmap)
    levs_xco2 = np.linspace(vmin_xco2, vmax_xco2, 256)
    clevs_xco2 = [sm_xco2.to_rgba(lev) for lev in levs_xco2]
    
    xco2_ctr = plt.contourf(x, y, xco2_masked, levs_xco2, colors=clevs_xco2, extend='both')
    
    xco2_cbar = plt.colorbar(xco2_ctr, orientation='horizontal', fraction=0.1, aspect=40)
    xco2_cbar.set_label('Xco$_2$ [ppm]')
    xco2_cbar.set_ticks(np.arange(vmin_xco2, vmax_xco2 + 1, 1))
    
    plt.title(datetime.strftime('EC-CAS Run %d %b %Y %H:%M:%S'))
    
    
    ##############################################################
    
    plt.sca(cld_ax)
    
    
    mission = retrievals.Mission(sim_file, *lattice_files, **kwargs)
    
    obs_time = time_utils.Time(datetime, mission.satellite.times[0].ref)        
        
    # find the closest apogee point to obs_time
    apogees = mission.satellite.get_apogees()
    apogee_ind = time_utils.closest_index(obs_time, apogees)
    
    # create the ObservationPeriod instance, and generate the Retrieval instances
    obs = retrievals.ObservationPeriod(mission, apogees[apogee_ind], mission.lattice_files[apogee_ind%2])
    obs.main_filter()
    obs.generate_retrievals()
    
    # find the closest segment of the observation period
    obs_ind = time_utils.closest_index(obs_time, obs.obs_middle)
    
    # clat, clon = centre
    proj_cld = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='c')
    
    # draw cloud data that was used to determine FOV locations
    obs.cloud_collection.show_clouds_ortho(obs.cloud_times[obs_ind], centre, map_bkgd=map_bkgd, out='')
    
    proj_cld.nightshade(datetime)
    
    # draw a red border around each of the selected FOVs
    for ret in obs.retrievals[obs_ind]:
        
        lats = np.concatenate([ret.pixel_lats[:,0], ret.pixel_lats[-1,:], ret.pixel_lats[::-1,-1], ret.pixel_lats[0,::-1]])
        lons = np.concatenate([ret.pixel_lons[:,0], ret.pixel_lons[-1,:], ret.pixel_lons[::-1,-1], ret.pixel_lons[0,::-1]])
        
        x,y = proj_cld(lons, lats)
        coords = np.vstack([x,y]).T
        
        if not np.sum(coords > 1e15):
        
            p = Polygon(coords, fill=False, edgecolor='r', zorder=10)
            plt.gca().add_patch(p)
        
    plt.title('FoV Selections {0} - {1} UTC'.format(obs.obs_times[obs_ind].strf('%d %B %Y %H:%M'), obs.obs_times[obs_ind+1].strf('%H:%M')))
    
    
    ##############################################################
    
    plt.sca(ret_ax)
    
    
    proj_ret = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='l')
    
    if map_bkgd == 'bluemarble':
        proj_ret.bluemarble()
    elif map_bkgd == 'etopo':
        proj_ret.etopo()
    elif map_bkgd == 'mask':
        proj_ret.drawlsmask(land_color='limegreen', ocean_color='dodgerblue', resolution='l')
        
        proj_ret.drawcoastlines(linewidth=0.75)
        proj_ret.drawcountries(linewidth=0.5)
        proj_ret.drawmeridians(np.arange(-180, 181, 30), latmax=90, linewidth=0.5)
        proj_ret.drawparallels(np.arange(-90, 91, 15), latmax=90, linewidth=0.5)
    else:
        raise ValueError('invalid map background specification')
    
    proj_ret.nightshade(datetime)
    
    
    sm_ret = ScalarMappable(Normalize(vmin=vmin_xco2, vmax=vmax_xco2), cmap=cmap)
    levs_ret = np.linspace(vmin_xco2, vmax_xco2, 256)
    clevs_ret = [sm_ret.to_rgba(lev) for lev in levs_ret]
    
    xco2_interp = RegularGridInterpolator((xco2_lats, xco2_lons), xco2, bounds_error=False, fill_value=None)
    
    for ret in obs.retrievals[obs_ind]:
                
        x,y = proj_ret(ret.pixel_lons, ret.pixel_lats)
                
        if not np.sum(x > 1e15):
        
            latlon_arr = np.dstack([ret.pixel_lats, ret.pixel_lons])
            xco2_ret = xco2_interp(latlon_arr)
            
            retmask = ret.valid_retrievals == 0
            xco2_ret_masked = np.ma.array(xco2_ret, mask=retmask)
            
            ret_ctr = plt.contourf(x, y, xco2_ret_masked, levs_ret, colors=clevs_ret, extend='both')
        
    
    ret_cbar = plt.colorbar(ret_ctr, orientation='horizontal', fraction=0.1, aspect=40)
    ret_cbar.set_label('Xco$_2$ [ppm]')
    ret_cbar.set_ticks(np.arange(vmin_xco2, vmax_xco2 + 1, 1))
    
    plt.title('AIM-North Retrievals {0} - {1} UTC'.format(obs.obs_times[obs_ind].strf('%d %B %Y %H:%M'), obs.obs_times[obs_ind+1].strf('%H:%M')))   
            
    
    ##############################################################
    
    
    plt.suptitle('AIM-North Observing Strategy')
    plt.subplots_adjust(wspace=0.05, left=0.05, right=0.95, top=1., bottom=0.1)
    
    cld_ax.set_position([0.35, 0.2525, 0.3, 0.675])
        
    
    if out == 'show':
        plt.show()
    elif out == '':
        pass
    else:
        plt.savefig(os.path.join('../figures/combined_plots/', out))
        plt.close()
Beispiel #27
0
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
# create new figure, axes instances.
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
# setup mercator map projection.
m = Basemap(llcrnrlon=-180.,llcrnrlat=-30.,urcrnrlon=180.,urcrnrlat=30.,\
            resolution='l',projection='merc',\
            # lat_0=40.,lon_0=-20.,lat_ts=20.

)
m.drawcoastlines()
m.fillcontinents()
m.drawparallels(np.arange(-30, 30, 20), labels=[1, 1, 0, 1])
# draw meridians
m.drawmeridians(np.arange(-180, 180, 60), labels=[1, 1, 0, 1])
date = datetime.utcnow()
m.nightshade(date)
ax.set_title('Great Circle from New York to London')
plt.show()
Beispiel #28
0
def geramapa(star, data, title, labelx, nameimg, mapstyle='1', resolution='l', centermap=None, lats=None, erro=None, ring=None, atm=None, clat=None, sitearq=None, fmt='png', dpi=100, mapsize=None):
    lon = star.ra - data.sidereal_time('mean', 'greenwich')
    center_map = EarthLocation(lon.value, star.dec.value)
    if not centermap == None:
        center_map = EarthLocation(centermap[0],centermap[1])
    m = Basemap(projection='ortho',lat_0=center_map.latitude.value,lon_0=center_map.longitude.value,resolution=resolution)
#    m = Basemap(projection='ortho',lat_0=center_map.latitude.value,lon_0=center_map.longitude.value,resolution=resolution,llcrnrx=-2000000.,llcrnry=-1500000.,urcrnrx=2000000.,urcrnry=1500000.)
#    kx = fig.add_axes([-0.003,-0.001,1.006,1.002])
#    kx.set_rasterization_zorder(1)
    m.nightshade(data.datetime, alpha=0.2, zorder=0.5)
    m.drawcoastlines(linewidth=0.5)
    m.drawcountries(linewidth=0.5)
    m.drawstates(linewidth=0.5)
    m.drawmeridians(np.arange(0,360,30))
    m.drawparallels(np.arange(-90,90,30))
    m.drawmapboundary()
    style = {'1': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'blue', 'rncolor':'blue', 'atcolor':'blue'},
             '2': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black'},
             '3': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black'},
             '4': {'ptcolor': 'red', 'lncolor': 'red', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black'},
             '5': {'ptcolor': 'red', 'lncolor': 'red', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black'}}
    if mapstyle == '2':
        m.drawmapboundary(fill_color='aqua')
        m.fillcontinents(color='coral',lake_color='aqua')
    elif mapstyle == '3':
        m.shadedrelief()
    elif mapstyle == '4':
        m.bluemarble()
    elif mapstyle == '5':
        m.etopo()
    if not lats == None:
        xs, ys = m(lats[0], lats[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, color=style[mapstyle]['lncolor'])
        xt, yt = m(lats[2], lats[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, color=style[mapstyle]['lncolor'])
    if not erro == None:
        xs, ys = m(erro[0], erro[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, '--', color=style[mapstyle]['ercolor'])
        xt, yt = m(erro[2], erro[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, '--', color=style[mapstyle]['ercolor'])
    if not ring == None:
        xs, ys = m(ring[0], ring[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, '--', color=style[mapstyle]['rncolor'])
        xt, yt = m(ring[2], ring[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, '--', color=style[mapstyle]['rncolor'])
    if not atm == None:
        xs, ys = m(atm[0], atm[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, color=style[mapstyle]['atcolor'])
        xt, yt = m(atm[2], atm[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, color=style[mapstyle]['atcolor'])
    if not clat == None:
        xc, yc = m(clon, clat)
        labe = [lab[i] for i in np.arange(len(lab)) if xc[i] < 1e+30]
        xc = [i for i in xc if i < 1e+30]
        yc = [i for i in yc if i < 1e+30]
        m.plot(xc, yc, 'o', color=style[mapstyle]['ptcolor'])

#    m.plot(ax,by, 'o', color=ptcolor, markersize=int(mapsize[0].value*20/46))
#    m.plot(ax2.to(u.m),by2.to(u.m), 'o', color=ptcolor, markersize=int(mapsize[0].value*12/46))
#    m.plot(ax3.to(u.m), by3.to(u.m), color='red')
#    m.plot(ax4.to(u.m), by4.to(u.m), color='red')
#    m.quiver(a-0*u.m,b-600000*u.m, 20, 0, width=0.005)

#    ax2 = a + dista*np.sin(pa) + [(i - datas).sec for i in temposplot]*u.s*vel*np.cos(paplus)
#    by2 = b + dista*np.cos(pa) - [(i - datas).sec for i in temposplot]*u.s*vel*np.sin(paplus)
#
#    labels = [i.iso.split()[1][0:8] for i in temposplot]
#    m.plot(ax2, by2, 'ro')
    
#    for label, axpt, bypt in zip(labe, xc, yc):
#        kx.text(axpt + 0, bypt + 350000, label, rotation=60, weight='bold')


#    if os.path.isfile(sitearq) == True:
#        xpt,ypt = m(sites['lon'],sites['lat'])
#        m.plot(xpt,ypt,'bo')
#        offset = [[xpt[0] + 100000,xpt[0] + 100000,xpt[0] + 100000,xpt[3] + 400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000],[10000,-30000,-60000,70000,30000,-20000,-70000,-30000,-70000]]
#        for i in np.arange(len(xpt)):
#            ax.text(offset[0][i],ypt[i]+offset[1][i],sites['nome'][i], weight='bold')

#    m.plot(ax5.to(u.m), by5.to(u.m), '--', color=dscolor, label='+-{} error'.format(erro))
#    m.plot(ax6.to(u.m), by6.to(u.m), '--', color=dscolor)
#    plt.legend(fontsize=mapsize[0].value*21/46)

    fig = plt.gcf()
    fig.set_size_inches(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value)
    plt.title(title, fontsize=mapsize[0].value*25/46, fontproperties='FreeMono', weight='bold')
    plt.xlabel(labelx, fontsize=mapsize[0].value*21/46, fontproperties='FreeMono', weight='bold')
    plt.savefig('{}.{}'.format(nameimg, fmt), format=fmt, dpi=dpi)
    print 'Gerado: {}.{}'.format(nameimg, fmt)
    plt.clf()
Beispiel #29
0
        map = Basemap(projection='ortho',
                      lat_0=0,
                      lon_0=lon,
                      resolution='l',
                      area_thresh=1000.)

        map.drawmapboundary()

        map.drawmeridians(np.arange(0, 360, 15), color="0.5", latmax=90)
        map.drawparallels(np.arange(-90, 90, 15), color="0.5", latmax=90)

        map.drawcoastlines()
        map.drawmapboundary(fill_color='aqua')
        map.fillcontinents(color='coral', lake_color='aqua')

        CS = map.nightshade(d)

        f = plt.gcf()
        f.set_size_inches(7.2, 7.2)

        plt.text(0.5,
                 0.95,
                 p,
                 transform=f.transFigure,
                 horizontalalignment="center",
                 fontsize="large")

        plt.text(0.5,
                 0.05,
                 "noon UTC",
                 transform=f.transFigure,
Beispiel #30
0
def _make_EICS_plots(dtime=None,
                     vplot_sized=False,
                     contour_den=8,
                     s_loc=False,
                     quiver_scale=30):
    """
    @Parameter: dtime input as a string
    @Parameter: s_loc input as a bool, which means the locations of the virtual stations.
    """
    dtype = 'EICS'

    if not os.path.exists(CONFIG['plots_dir']):
        os.makedirs(CONFIG['plots_dir'])
    dtime_range = [dtime, dtime]
    pathformat_prefix = dtype + '/%Y/%m/'
    pathformat_unzipped = pathformat_prefix + '%d/' + dtype + '%Y%m%d_%H%M%S.dat'
    filename_unzipped = dailynames(file_format=pathformat_unzipped,
                                   trange=dtime_range,
                                   res=10)
    out_files_unzipped = [
        CONFIG['local_data_dir'] + rf_res for rf_res in filename_unzipped
    ]
    Data_Days_time = read_data_files(out_files=out_files_unzipped,
                                     dtype=dtype,
                                     out_type='df')

    J_comp = Data_Days_time['Jy']
    Jc_max, Jc_min = J_comp.max(), J_comp.min()
    Jcm_abs = max(abs(Jc_max), abs(Jc_min))
    contour_density = np.linspace(-Jcm_abs, Jcm_abs, num=contour_den)
    tp = dtime
    datetime_tp = tp[0:4] + tp[5:7] + tp[8:10] + '_' + tp[11:13] + tp[
        14:16] + tp[17:19]
    lon = Data_Days_time['longitude']
    lat = Data_Days_time['latitude']
    Jx = Data_Days_time['Jx']  # Note: positive is Northward
    Jy = Data_Days_time['Jy']  # Note: positive is Eastward

    # plot 1:
    # plot map ground (North hemisphere)
    fig1 = plt.figure(figsize=(8, 8))
    ax1 = plt.gca()

    m = Basemap(projection='lcc',
                resolution='c',
                width=8E6,
                height=8E6,
                lat_0=60,
                lon_0=-100)
    # draw coastlines, country boundaries, fill continents.
    m.drawcoastlines(linewidth=0.25)
    m.drawcountries(linewidth=0.25)
    m.fillcontinents(color='None', lake_color='None')
    # draw the edge of the map projection region (the projection limb)
    m.drawmapboundary(fill_color=None)
    # m.drawgreatcircle(-100,0,0,90)
    m.drawlsmask()
    # m.bluemarble()
    m.shadedrelief()
    # draw parallels and meridians.
    # label parallels on right and top
    # meridians on bottom and left
    parallels = np.arange(0., 81, 10.)
    # labels = [left,right,top,bottom]
    m.drawparallels(parallels, labels=[False, True, True, False])
    meridians = np.arange(10., 351., 20.)
    m.drawmeridians(meridians, labels=[True, False, False, True])
    date_nightshade = datetime.strptime(dtime, '%Y-%m-%d/%H:%M:%S')
    m.nightshade(date=date_nightshade)
    draw_map(m)

    # plot vector field:

    lon = lon.to_numpy()
    lat = lat.to_numpy()
    Jx = Jx.to_numpy()  # Note: positive is Northward
    Jy = Jy.to_numpy()  # Note: positive is Eastward
    Jx_uni = Jx / np.sqrt(Jx**2 + Jy**2)
    Jy_uni = Jy / np.sqrt(Jx**2 + Jy**2)
    n = -2
    color = np.sqrt(((Jx_uni - n) / 2)**2 + ((Jy_uni - n) / 2)**2)
    if vplot_sized == False:
        qv = m.quiver(
            lon,
            lat,
            Jx_uni,
            Jy_uni,
            color,
            headlength=7,
            latlon=True,
            cmap='GnBu')  # autumn_r #, color=cm(norm(o)))#, cmap = 'jet')
        plt.colorbar()
    else:
        Jy_rot, Jx_rot, x, y = m.rotate_vector(Jy, Jx, lon, lat, returnxy=True)
        qv = m.quiver(lon,
                      lat,
                      Jy_rot,
                      Jx_rot,
                      headlength=7,
                      latlon=True,
                      scale_units='dots',
                      scale=quiver_scale)  # , transform='lcc')

        qk = ax1.quiverkey(qv,
                           0.3,
                           -0.1,
                           100,
                           r'$100 \ mA/m$',
                           labelpos='E',
                           coordinates='data')  # figure

    plt.title(label='EICS ' + tp, fontsize=20, color="black", pad=20)
    plt.tight_layout()
    plt.savefig(CONFIG['plots_dir'] + 'EICS' + '_vector_' +
                date_nightshade.strftime('%Y%m%d%H%M%S') + '.jpeg')
    plt.show()

    # plot 2: contour plot
    # plot map ground (North hemisphere)
    fig2 = plt.figure(figsize=(8, 8))
    ax2 = plt.gca()
    m = Basemap(projection='lcc',
                resolution='c',
                width=8E6,
                height=8E6,
                lat_0=60,
                lon_0=-100)
    # draw coastlines, country boundaries, fill continents.
    m.drawcoastlines(linewidth=0.25)
    m.drawcountries(linewidth=0.25)
    m.fillcontinents(color='None', lake_color='None')
    # draw the edge of the map projection region (the projection limb)
    m.drawmapboundary(fill_color=None)
    m.drawlsmask()
    m.shadedrelief()
    # draw parallels and meridians.
    # label parallels on right and top
    # meridians on bottom and left
    parallels = np.arange(0., 81, 10.)
    m.drawparallels(parallels, labels=[False, True, True, False])
    meridians = np.arange(10., 351., 20.)
    m.drawmeridians(meridians, labels=[True, False, False, True])

    date_nightshade = datetime.strptime(dtime, '%Y-%m-%d/%H:%M:%S')
    # m.nightshade(date=date_nightshade, alpha = 0.0)

    delta = 0.25
    lons_dd, lats_dd, tau, dec = daynight_terminator(date_nightshade, delta,
                                                     m.lonmin, m.lonmax)
    xy = [lons_dd, lats_dd]
    xy = np.array(xy)
    xb, yb = xy[0], xy[1]
    m.plot(xb, yb, marker=None, color='m',
           latlon=True)  # for dawn-dusk circle line

    # Plot the noon-midnight line.
    n_interval = len(lons_dd)
    ni_half = int(np.floor(len(lons_dd) / 2))
    ni_otherhalf = n_interval - ni_half

    noon_midnight = noon_midnight_meridian(dtime, delta)

    m.plot(noon_midnight['lons_noon'],
           noon_midnight['lats_noon'],
           marker=None,
           color='deepskyblue',
           latlon=True)  # noon semi-circle

    m.plot(noon_midnight['lons_midnight'],
           noon_midnight['lats_midnight'],
           marker=None,
           color='k',
           latlon=True)  # midnight semi-circle

    draw_map(m)

    Jy_log = Jy / np.abs(Jy) * np.log10(np.abs(Jy))
    norm_cb = CenteredNorm()
    # norm_cb = NoNorm()
    # norm_cb = CenteredNorm(vmin=Jy.min(), vcenter=0, vmax=Jy.max())
    # use Jy for the contour map, not Jy_rot.
    ctrf = m.contourf(lon,
                      lat,
                      Jy,
                      contour_density,
                      latlon=True,
                      tri=True,
                      cmap='jet_r',
                      norm=norm_cb)
    ##ctrf = m.contourf(lon, lat, Jy, contour_density, latlon=True, tri=True, cmap='jet_r', norm=norm_cb)
    # -------------
    if s_loc:
        m.scatter(lon, lat, latlon=True, marker='*', c='black')
    # -------------
    cb = m.colorbar(matplotlib.cm.ScalarMappable(norm=norm_cb, cmap='jet_r'),
                    pad='15%')
    cb.set_label(r'$\mathit{J}_y \  (mA/m)$')
    ax_cb = cb.ax
    text = ax_cb.yaxis.label
    font_cb = matplotlib.font_manager.FontProperties(family='times new roman',
                                                     style='italic',
                                                     size=20)
    text.set_font_properties(font_cb)
    plt.title(label='EICS ' + tp, fontsize=20, color="black", pad=20)
    plt.tight_layout()
    plt.savefig(CONFIG['plots_dir'] + 'EICS' + '_contour_' +
                date_nightshade.strftime('%Y%m%d%H%M%S') + '.jpeg')
    plt.show()

    print('EICS plots completed!')
    return
Beispiel #31
0
def bluemarble_daynight(date, scale):
    mpl.rcParams['savefig.pad_inches'] = 0
    # Define Bluemarble and Nightshade objects
    #fig, axes = plt.subplots(1, figsize=(12,8), frameon=False)
    fig = plt.figure(figsize=(12, 8))
    axes = plt.axes([0, 0, 1, 1], frameon=False)
    axes.get_xaxis().set_visible(False)
    axes.get_yaxis().set_visible(False)
    plt.autoscale(tight=True)
    m = Basemap(projection='cyl', resolution=None, area_thresh=None, ax=axes)
    bm = m.bluemarble(scale=scale)
    ns = m.nightshade(date, alpha=0.5)

    bm_rgb = bm.get_array()
    bm_ext = bm.get_extent()

    axes.cla()

    # Get the x and y index spacing
    x = np.linspace(bm_ext[0], bm_ext[1], bm_rgb.shape[1])
    y = np.linspace(bm_ext[2], bm_ext[3], bm_rgb.shape[0])

    # Define coordinates of the Bluemarble image
    x3d, y3d = np.meshgrid(x, y)
    pts = np.hstack((x3d.flatten()[:, np.newaxis], y3d.flatten()[:,
                                                                 np.newaxis]))

    # Find which coordinates fall in Nightshade
    # The following could be tidied up as there should only ever one polygon. Although
    # the length of ns.collections is 3? I'm sure there's a better way to do this.
    paths, polygons = [], []
    for i, polygons in enumerate(ns.collections):
        for j, paths in enumerate(polygons.get_paths()):
            #print j, i
            msk = paths.contains_points(pts)

    # Redefine mask
    msk = np.reshape(msk, bm_rgb[:, :, 0].shape)
    msk_s = np.zeros(msk.shape)
    msk_s[~msk] = 1.

    # Smooth interface between Night and Day
    for s in range(
            bm_rgb.shape[1] // 50
    ):  # Make smoothing between day and night a function of Bluemarble resolution
        msk_s = 0.25 * (  np.vstack( (msk_s[-1,:            ], msk_s[:-1, :            ]) )  \
                        + np.vstack( (msk_s[1:,:            ], msk_s[0  , :            ]) )  \
                        + np.hstack( (msk_s[: ,0, np.newaxis], msk_s[:  , :-1          ]) )  \
                        + np.hstack( (msk_s[: ,1:           ], msk_s[:  , -1,np.newaxis]) ) )

    # Define new RGBA array
    bm_rgba = np.dstack((bm_rgb, msk_s))

    # Plot up Bluemarble Nightshade
    m = Basemap(projection='cyl', resolution=None, area_thresh=None, ax=axes)
    bm_n = m.warpimage('/home/pi/Mimic/Pi/imgs/orbit/earth_lights_lrg.jpg',
                       scale=scale)
    bm_d = m.imshow(bm_rgba)
    plt.savefig('/home/pi/Mimic/Pi/imgs/orbit/map.jpg',
                bbox_inches='tight',
                pad_inches=0)
Beispiel #32
0
def geramapa(star,
             data,
             title,
             labelx,
             nameimg,
             mapstyle='1',
             resolution='l',
             centermap=None,
             lats=None,
             erro=None,
             ring=None,
             atm=None,
             clat=None,
             sitearq=None,
             fmt='png',
             dpi=100,
             mapsize=None,
             cpoints=60,
             off=0):
    lon = star.ra - data.sidereal_time('mean', 'greenwich')
    center_map = EarthLocation(lon.value, star.dec.value)
    if not centermap == None:
        center_map = EarthLocation(centermap[0], centermap[1])
    m = Basemap(projection='ortho',
                lat_0=center_map.latitude.value,
                lon_0=center_map.longitude.value,
                resolution=resolution)
    #    m = Basemap(projection='ortho',lat_0=center_map.latitude.value,lon_0=center_map.longitude.value,resolution=resolution,llcrnrx=-2000000.,llcrnry=-1500000.,urcrnrx=2000000.,urcrnry=1500000.)
    #    kx = fig.add_axes([-0.003,-0.001,1.006,1.002])
    #    kx.set_rasterization_zorder(1)
    m.nightshade(data.datetime, alpha=0.3,
                 zorder=0.5)  ## desenha a sombra da noite
    m.drawcoastlines(linewidth=0.5)  ## desenha as linhas da costa
    m.drawcountries(linewidth=0.5)  ## desenha os paises
    m.drawstates(linewidth=0.5)  ## Desenha os estados
    m.drawmeridians(np.arange(0, 360, 30))  ## desenha os meridianos
    m.drawparallels(np.arange(-90, 90, 30))  ## desenha os paralelos
    m.drawmapboundary()  ## desenha o contorno do mapa
    style = {
        '1': {
            'ptcolor': 'red',
            'lncolor': 'blue',
            'ercolor': 'blue',
            'rncolor': 'blue',
            'atcolor': 'blue',
            'outcolor': 'red'
        },
        '2': {
            'ptcolor': 'red',
            'lncolor': 'blue',
            'ercolor': 'red',
            'rncolor': 'black',
            'atcolor': 'black',
            'outcolor': 'red'
        },
        '3': {
            'ptcolor': 'red',
            'lncolor': 'blue',
            'ercolor': 'red',
            'rncolor': 'black',
            'atcolor': 'black',
            'outcolor': 'red'
        },
        '4': {
            'ptcolor': 'red',
            'lncolor': 'red',
            'ercolor': 'red',
            'rncolor': 'black',
            'atcolor': 'black',
            'outcolor': 'red'
        },
        '5': {
            'ptcolor': 'red',
            'lncolor': 'red',
            'ercolor': 'red',
            'rncolor': 'black',
            'atcolor': 'black',
            'outcolor': 'red'
        }
    }
    if mapstyle == '2':
        m.drawmapboundary(fill_color='aqua')
        m.fillcontinents(color='coral', lake_color='aqua')
    elif mapstyle == '3':
        m.shadedrelief()
    elif mapstyle == '4':
        m.bluemarble()
    elif mapstyle == '5':
        m.etopo()
    if not lats == None:
        xs, ys = m(lats[0], lats[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, color=style[mapstyle]['lncolor'])
        xt, yt = m(lats[2], lats[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, color=style[mapstyle]['lncolor'])
        m.plot(lats[4],
               lats[5],
               color=style[mapstyle]['outcolor'],
               clip_on=False,
               zorder=-0.2)
        m.plot(lats[6],
               lats[7],
               color=style[mapstyle]['outcolor'],
               clip_on=False,
               zorder=-0.2)
#    else:
#        m.plot(lats[4], lats[5], color=style[mapstyle]['outcolor'], clip_on=False, zorder=0.2)
#        m.plot(lats[6], lats[7], color=style[mapstyle]['outcolor'], clip_on=False, zorder=0.2)
    if not erro == None:
        xs, ys = m(erro[0], erro[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, '--', color=style[mapstyle]['ercolor'])
        xt, yt = m(erro[2], erro[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, '--', color=style[mapstyle]['ercolor'])
    if not ring == None:
        xs, ys = m(ring[0], ring[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, '--', color=style[mapstyle]['rncolor'])
        xt, yt = m(ring[2], ring[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, '--', color=style[mapstyle]['rncolor'])
    if not atm == None:
        xs, ys = m(atm[0], atm[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, color=style[mapstyle]['atcolor'])
        xt, yt = m(atm[2], atm[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, color=style[mapstyle]['atcolor'])
    if not clat == None:
        xc, yc, lab = [], [], []
        cp = Time(clat[5], format='iso')
        vec = np.arange(0, (cp[-1] - data).sec, cpoints)
        vec = np.sort(np.concatenate((vec, -vec[1:]), axis=0)) * u.s
        for i in vec:
            g = data + TimeDelta(i) + TimeDelta(off * u.s)
            if g.iso in clat[2]:
                a = np.where(np.array(clat[2]) == g.iso)
                x, y = m(np.array(clat[0])[a], np.array(clat[1])[a])
                xc.append(x)
                yc.append(y)
                lab.append(g.iso.split()[1][0:8])
            elif g.iso in clat[5]:
                a = np.where(np.array(clat[5]) == g.iso)
                xc.append(np.array(clat[3])[a])
                yc.append(np.array(clat[4])[a])
                lab.append(g.iso.split()[1][0:8])
            else:
                if len(clat[2]) == 0:
                    a = [0]
                else:
                    co = Time(clat[2], format='iso')
                    a = np.argsort(np.absolute(co - g))[0:2]
                if 0 not in a and len(co) - 1 not in a:
                    b = np.absolute((co[a] - g).sec)
                    x, y = m(np.array(clat[0])[a], np.array(clat[1])[a])
                    xc.append(np.sum(x * (1 / b)) / np.sum(1 / b))
                    yc.append(np.sum(y * (1 / b)) / np.sum(1 / b))
                    lab.append(g.iso.split()[1][0:8])
                else:
                    co = Time(clat[5], format='iso')
                    a = np.argsort(np.absolute(co - g))[0:2]
                    b = np.absolute((co[a] - g).sec)
                    xc.append(
                        np.sum(np.array(clat[3])[a] * (1 / b)) / np.sum(1 / b))
                    yc.append(
                        np.sum(np.array(clat[4])[a] * (1 / b)) / np.sum(1 / b))
                    lab.append(g.iso.split()[1][0:8])
        m.plot(xc,
               yc,
               'o',
               color=style[mapstyle]['ptcolor'],
               clip_on=False,
               markersize=mapsize[0].value * 8 / 46)
        m.plot(clat[6][0],
               clat[6][1],
               'o',
               color=style[mapstyle]['ptcolor'],
               clip_on=False,
               markersize=mapsize[0].value * 20 / 46)


#    for label, axpt, bypt in zip(lab, xc, yc):
#        plt.text(axpt + 0, bypt + 350000, label, rotation=60, weight='bold')

#    m.plot(ax,by, 'o', color=ptcolor, markersize=int(mapsize[0].value*20/46))
#    m.plot(ax2.to(u.m),by2.to(u.m), 'o', color=ptcolor, markersize=int(mapsize[0].value*12/46))
#    m.plot(ax3.to(u.m), by3.to(u.m), color='red')
#    m.plot(ax4.to(u.m), by4.to(u.m), color='red')
#    m.quiver(a-0*u.m,b-600000*u.m, 20, 0, width=0.005)

#    ax2 = a + dista*np.sin(pa) + [(i - datas).sec for i in temposplot]*u.s*vel*np.cos(paplus)
#    by2 = b + dista*np.cos(pa) - [(i - datas).sec for i in temposplot]*u.s*vel*np.sin(paplus)
#
#    labels = [i.iso.split()[1][0:8] for i in temposplot]
#    m.plot(ax2, by2, 'ro')

#    if os.path.isfile(sitearq) == True:
#        xpt,ypt = m(sites['lon'],sites['lat'])
#        m.plot(xpt,ypt,'bo')
#        offset = [[xpt[0] + 100000,xpt[0] + 100000,xpt[0] + 100000,xpt[3] + 400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000],[10000,-30000,-60000,70000,30000,-20000,-70000,-30000,-70000]]
#        for i in np.arange(len(xpt)):
#            ax.text(offset[0][i],ypt[i]+offset[1][i],sites['nome'][i], weight='bold')

#    m.plot(ax5.to(u.m), by5.to(u.m), '--', color=dscolor, label='+-{} error'.format(erro))
#    m.plot(ax6.to(u.m), by6.to(u.m), '--', color=dscolor)
#    plt.legend(fontsize=mapsize[0].value*21/46)

    fig = plt.gcf()
    fig.set_size_inches(mapsize[0].to(u.imperial.inch).value,
                        mapsize[1].to(u.imperial.inch).value)
    plt.title(title,
              fontsize=mapsize[0].value * 25 / 46,
              fontproperties='FreeMono',
              weight='bold')
    plt.xlabel(labelx,
               fontsize=mapsize[0].value * 21 / 46,
               fontproperties='FreeMono',
               weight='bold')
    plt.savefig('{}.{}'.format(nameimg, fmt), format=fmt, dpi=dpi)
    print 'Gerado: {}.{}'.format(nameimg, fmt)
    plt.clf()
Beispiel #33
0
    def to_run(self):
        """Interactive plotting of satellite postion after data generation.
           This is the function that the thread runs.

        """

        # Setup lat long of telescope
        home = ephem.Observer()

        # NITK credentials
        home.long = np.deg2rad(74.7421430)  # +E
        home.lat = np.deg2rad(13.3408810)  # +N
        home.elevation = 0  # meters
        home.date = datetime.datetime.now()

        # Read TLE file
        tlefile = open('./TLE/' + self.id + '.txt', 'r').read()
        tlesplit = tlefile.split('\n')

        assert len(tlesplit) >= 3

        satellite = ephem.readtle(tlesplit[0], tlesplit[1], tlesplit[2])

        # Make some datetimes
        # We will plot the path for thepast hour then start real time tracking
        # We pre compute values for 24 hours
        current_time = datetime.datetime.now()
        past_time = current_time + timedelta(hours=-1)
        dt = [
            current_time + timedelta(seconds=1 * x)
            for x in range(0, 24 * 60 * 60)
        ]
        dt_past = [
            past_time + timedelta(seconds=1 * x) for x in range(0, 60 * 60)
        ]

        # Compute satellite locations at each datetime
        sat_lat, sat_lon, sat_latp, sat_lonp = [], [], [], []
        for date in dt:
            home.date = date
            satellite.compute(home)
            sat_lon.append(np.rad2deg(satellite.sublong))
            sat_lat.append(np.rad2deg(satellite.sublat))

        for date in dt_past:
            home.date = date
            satellite.compute(home)
            sat_lonp.append(np.rad2deg(satellite.sublong))
            sat_latp.append(np.rad2deg(satellite.sublat))

        # Calibrate everything to have positive values
        for i in range(len(sat_lon)):
            if sat_lon[i] < 0:
                sat_lon[i] = 360 + sat_lon[i]
        for i in range(len(sat_lonp)):
            if sat_lonp[i] < 0:
                sat_lonp[i] = 360 + sat_lonp[i]

        # miller projection using Basemap
        mymap = Basemap(projection='mill', lon_0=180)

        # plot coastlines, draw label meridians and parallels.
        mymap.drawcoastlines()
        mymap.drawparallels(np.arange(-90, 90, 30), labels=[1, 0, 0, 0])
        mymap.drawmeridians(np.arange(mymap.lonmin, mymap.lonmax + 30, 60),
                            labels=[0, 0, 0, 1])

        # fill continents 'coral' (with zorder=0), color wet areas 'aqua'
        mymap.drawmapboundary(fill_color='aqua')

        # shade the night areas, with alpha transparency so the
        # mymap shows through. Use current time in UTC.
        # Prepare values to plot
        date = datetime.datetime.utcnow()

        # convert to map projection co-ordinates
        x, y = mymap(sat_lon, sat_lat)
        xp, yp = mymap(sat_lonp, sat_latp)

        # Convert to numpy arrays
        # atleast_1d makes sure arrays are atleast 1-d, unnecessary check for scalars
        x = np.atleast_1d(x)
        y = np.atleast_1d(y)
        xp = np.atleast_1d(xp)
        yp = np.atleast_1d(yp)

        # compute night shade for the given date
        CS = mymap.nightshade(date)

        # Set some properties for the plot window
        mng = plt.get_current_fig_manager()
        mng.window.showMaximized()

        # Plot the past hour data
        plt.scatter(xp, yp, color='y', s=5, label="Past Hour")

        # Now we start plotting interactively
        plt.ion()
        plt.scatter(x[0], y[0], color='#FF3F35', label="Real time")

        # Position legend and set transparency
        leg = plt.legend(fancybox=True, shadow=True, loc=4)
        leg.get_frame().set_alpha(0.1)

        # We have calculated data for every second for 24 hours from current time
        # We plot eachdata point with one second delaytosimulate real time plotting

        for i in range(1, len(sat_lon)):
            plt.scatter(x[i], y[i], color='#FF3F35', label="Real time")
            plt.pause(1)

        # If done plotting everything, just pause
        while self.running:
            plt.pause(1)

        plt.close('all')
Beispiel #34
0
            rsphere=(6378137.00,6356752.3142),\
            resolution='l',area_thresh=1000.,projection='lcc',\
            lat_1=50.,lon_0=-107.,ax=ax)
# transform to nx x ny regularly spaced 5km native projection grid
nx = int((m.xmax-m.xmin)/5000.)+1; ny = int((m.ymax-m.ymin)/5000.)+1
# topodat = m.transform_scalar(topoin,lons,lats,nx,ny)
# plot image over map with imshow.
# im = m.imshow(topodat,cm.GMT_haxby)
# draw coastlines and political boundaries.
m.drawcoastlines()
m.drawcountries()
m.drawstates()
# draw parallels and meridians.
# label on left and bottom of map.
parallels = np.arange(0.,80,20.)
m.drawparallels(parallels,labels=[1,0,0,1])
meridians = np.arange(10.,360.,30.)
m.drawmeridians(meridians,labels=[1,0,0,1])
# add colorbar
# cb = m.colorbar(im,"right", size="5%", pad='2%')
ax.set_title('ETOPO5 Topography - Lambert Conformal Conic')

from datetime import datetime

date = datetime.utcnow()
CS=m.nightshade(date)




plt.show()
Beispiel #35
0
    # We now know how many counts there are per bin on the grid. We can now plot the grid locations with number of counts
    lat_bin = gridx[np.where(grid > 0)[0]]
    lon_bin = gridy[np.where(grid > 0)[1]]
    count_bin = grid[np.where(grid > 0)]

    # Make a plot of the world
    plt.figure(figsize=(30, 15))
    map = Basemap()
    map.drawcoastlines()
    map.drawparallels(np.arange(-90, 90, 30), labels=[1, 0, 0, 0])
    map.drawmeridians(np.arange(map.lonmin, map.lonmax + 30, 60),
                      labels=[0, 0, 0, 1])
    map.fillcontinents('white', lake_color='white')
    map.drawcountries(linewidth=1, linestyle='solid', color='black', zorder=30)
    date = datetime.utcnow()
    CS = map.nightshade(date.replace(hour=8, minute=0, second=0,
                                     microsecond=0))
    plt.title('Wikipedia Edit Locations')
    # Overlay the lat and long bins
    # Scale the size and color so they are sensible
    size = count_bin
    plt.scatter(lat_bin,
                lon_bin,
                s=size,
                alpha=0.8,
                c=count_bin,
                cmap='inferno',
                zorder=10)
    plt.colorbar(fraction=0.023, pad=0.04)
    plt.savefig('./Report/Images/editlocations.png')
    print './Report/Images/editlocations.png'
    plt.clf()
    def to_run(self):
        # Setup lat long of telescope
        home = ephem.Observer()

        home.long = np.deg2rad(74.7421430)  # +E
        home.lat = np.deg2rad(13.3408810)  # +N
        home.elevation = 0  # meters
        home.date = datetime.datetime.now()

        # Always get the latest ISS TLE data from:
        # http://spaceflight.nasa.gov/realdata/sightings/SSapplications/Post/JavaSSOP/orbit/ISS/SVPOST.html
        iss = ephem.readtle(
            'ISS',
            '1 25544U 98067A   16274.50033672  .00016717  00000-0  10270-3 0  9003',
            '2 25544  51.6383 252.7108 0006713  21.8902 338.2536 15.54019889 21364'
        )

        # Make some datetimes
        current_time = datetime.datetime.now()
        past_time = current_time + timedelta(hours=-1)
        dt = [
            current_time + timedelta(seconds=1 * x)
            for x in range(0, 24 * 60 * 60)
        ]
        dt_past = [
            past_time + timedelta(seconds=1 * x) for x in range(0, 60 * 60)
        ]

        # Compute satellite locations at each datetime
        sat_lat, sat_lon, sat_latp, sat_lonp = [], [], [], []
        for date in dt:
            home.date = date
            iss.compute(home)
            sat_lon.append(np.rad2deg(iss.sublong))
            sat_lat.append(np.rad2deg(iss.sublat))

        for date in dt_past:
            home.date = date
            iss.compute(home)
            sat_lonp.append(np.rad2deg(iss.sublong))
            sat_latp.append(np.rad2deg(iss.sublat))

        for i in range(len(sat_lon)):
            if sat_lon[i] < 0:
                sat_lon[i] = 360 + sat_lon[i]
        for i in range(len(sat_lonp)):
            if sat_lonp[i] < 0:
                sat_lonp[i] = 360 + sat_lonp[i]

        # miller projection
        map = Basemap(projection='mill', lon_0=180)
        # plot coastlines, draw label meridians and parallels.
        map.drawcoastlines()
        map.drawparallels(np.arange(-90, 90, 30), labels=[1, 0, 0, 0])
        map.drawmeridians(np.arange(map.lonmin, map.lonmax + 30, 60),
                          labels=[0, 0, 0, 1])
        # fill continents 'coral' (with zorder=0), color wet areas 'aqua'
        map.drawmapboundary(fill_color='aqua')
        # map.fillcontinents(color='coral',lake_color='aqua')
        # shade the night areas, with alpha transparency so the
        # map shows through. Use current time in UTC.
        date = datetime.datetime.utcnow()
        x, y = map(sat_lon, sat_lat)
        x = np.atleast_1d(x)
        y = np.atleast_1d(y)

        xp, yp = map(sat_lonp, sat_latp)
        xp = np.atleast_1d(xp)
        yp = np.atleast_1d(yp)

        CS = map.nightshade(date)

        plt.scatter(xp, yp, color='y', s=5, label="Past Hour")
        plt.ion()

        for i in range(len(sat_lon)):
            plt.scatter(x[i], y[i], color='r', label="realtime")
            plt.pause(1)

        while self.running:
            plt.pause(1)

        # plt.title('Day/Night Map for %s (UTC)' % date.strftime("%d %b %Y %H:%M:%S"))
        # plt.show()

        plt.close('all')
    def map_plot(self, time, TLE):
        start_mode = self.mode_choice.GetSelection()
        m = Basemap(projection='mill',
                    area_thresh=1000.0,
                    llcrnrlat=south,
                    urcrnrlat=north,
                    llcrnrlon=west,
                    urcrnrlon=east)
        #m.shadedrelief()
        im = Image.open(resource_path('default_map.png'))
        m.imshow(im, alpha=1)
        m.nightshade(time + datetime.timedelta(hours=10))
        #m.drawcoastlines()
        # 一分ごとの人工衛星の位置をプロット
        time_list = []
        for t in range(-10, 100):
            time_list.append(time + datetime.timedelta(minutes=t))
        for t in time_list:
            satellite = ephem.readtle(TLE[0], TLE[1], TLE[2])
            satellite.compute(t)
            latitude = satellite.sublat / ephem.degree
            longitude = satellite.sublong / ephem.degree - 150
            if longitude < -180:
                longitude += 360
            x1, y1 = m(longitude, latitude)
            m.plot(x1, y1, marker=".", markersize=1, c='blue')
        if self.mode_choice.GetSelection() != start_mode:
            if self.mode_choice.GetSelection():
                time = datetime.datetime.utcnow()
            else:
                time = self.get_time()
            self.map_plot(time, TLE)
            return 0
        satellite = ephem.readtle(TLE[0], TLE[1], TLE[2])
        satellite.compute(time)
        latitude = satellite.sublat / ephem.degree
        longitude = satellite.sublong / ephem.degree - 150
        if longitude < -180:
            longitude += 360
        earth_radius = 6371000.
        sat_loc = (latitude, longitude)
        # define the position of the satellite
        orbit = Orbital(TLE[0], line1=TLE[1], line2=TLE[2])
        lon_dum, lat_dum, altitude = orbit.get_lonlatalt(time)
        print(altitude)
        position = [altitude * 1000, latitude, longitude]

        radius = math.degrees(
            math.acos(earth_radius / (earth_radius + position[0])))
        print(longitude)
        x1, y1 = m(longitude, latitude)
        m.plot(x1, y1, marker="*", markersize=5, c='red')
        if longitude < -90:
            diff = longitude - (-180)
            m = Basemap(projection='mill',
                        area_thresh=1000.0,
                        llcrnrlat=south,
                        urcrnrlat=north,
                        llcrnrlon=0,
                        urcrnrlon=360)
            m.tissot(diff, latitude, radius, 100, facecolor='white', alpha=0.5)
            m = Basemap(projection='mill',
                        area_thresh=1000.0,
                        llcrnrlat=south,
                        urcrnrlat=north,
                        llcrnrlon=-360,
                        urcrnrlon=0)
            m.tissot(diff, latitude, radius, 100, facecolor='white', alpha=0.5)
        elif longitude > 90:
            diff = longitude - 180
            m = Basemap(projection='mill',
                        area_thresh=1000.0,
                        llcrnrlat=south,
                        urcrnrlat=north,
                        llcrnrlon=0,
                        urcrnrlon=360)
            m.tissot(diff, latitude, radius, 100, facecolor='white', alpha=0.5)
            m = Basemap(projection='mill',
                        area_thresh=1000.0,
                        llcrnrlat=south,
                        urcrnrlat=north,
                        llcrnrlon=-360,
                        urcrnrlon=0)
            m.tissot(diff, latitude, radius, 100, facecolor='white', alpha=0.5)
        else:
            m.tissot(longitude,
                     latitude,
                     radius,
                     100,
                     facecolor='white',
                     alpha=0.5)
        plt.gca().spines['right'].set_visible(False)
        plt.gca().spines['top'].set_visible(False)
        plt.gca().spines['left'].set_visible(False)
        plt.gca().spines['bottom'].set_visible(False)
        plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
        buf = io.BytesIO()
        plt.savefig(buf,
                    format='png',
                    dpi=300,
                    transparent=False,
                    bbox_inches='tight',
                    pad_inches=0)
        #plt.savefig('map.png',format='png', dpi = 600, transparent = False, bbox_inches = 'tight', pad_inches = 0)
        plt.close()
        buf.seek(0)
        self.output_map = buf
        if self.mode_choice.GetSelection() != start_mode:
            if self.mode_choice.GetSelection():
                time = datetime.datetime.utcnow()
            else:
                time = self.get_time()
            self.map_plot(time, TLE)
            return 0

        self.Image = wx.Image(buf, wx.BITMAP_TYPE_ANY)
        self.wxImage = wx.Bitmap(self.Image)  #画像リサイズ対象=wx.Bitmap
        self.wxImage_re = scale_bitmap(self.wxImage, int(16 * self.ratio),
                                       int(9 * self.ratio))
        self.tracking_map.SetBitmap(self.wxImage_re)
Beispiel #38
0
import numpy as np
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from datetime import datetime
# miller projection 
map = Basemap(projection='mill',lon_0=180)
# plot coastlines, draw label meridians and parallels.
map.drawcoastlines()
map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0])
map.drawmeridians(np.arange(map.lonmin,map.lonmax+30,60),labels=[0,0,0,1])
# fill continents 'coral' (with zorder=0), color wet areas 'aqua'
map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='coral',lake_color='aqua')
# shade the night areas, with alpha transparency so the 
# map shows through. Use current time in UTC.
date = datetime.utcnow()
CS=map.nightshade(date)
plt.title('Day/Night Map for %s (UTC)' % date.strftime("%d %b %Y %H:%M:%S"))
plt.show()
Beispiel #39
0
    def compute(elem):
        print("============== Gerando o mapa para a predicao ==============")
        print("Predicao: [ %s ] Star RA: [ %s ] Dec: [ %s ]" %(elem, stars[elem].ra, stars[elem].dec))

        r = 6370997.0

        print("r: %s" % r)

########## aplica offsets ######
        print("-------------- Aplica Offsets --------------")

        off_ra = 0.0*u.mas
        off_de = 0.0*u.mas
        ob_ra = 0.0*u.mas
        ob_de = 0.0*u.mas
        if 'off_o' in kwargs.keys():
            off_ra = off_ra + kwargs['off_o'][0]*u.mas
            off_de = off_de + kwargs['off_o'][1]*u.mas
            ob_ra = ob_off_ra[elem] + kwargs['off_o'][0]*u.mas
            ob_de = ob_off_de[elem] + kwargs['off_o'][1]*u.mas
        st_off_ra = st_off_de = 0.0*u.mas
        if 'off_s' in kwargs.keys():
            off_ra = off_ra - kwargs['off_s'][0]*u.mas
            off_de = off_de - kwargs['off_s'][1]*u.mas
            st_off_ra = kwargs['off_s'][0]*u.mas
            st_off_de = kwargs['off_s'][1]*u.mas
        dca = off_ra*np.sin(posa[elem]) + off_de*np.cos(posa[elem])
        dt = ((off_ra*np.cos(posa[elem]) - off_de*np.sin(posa[elem])).to(u.rad)*dist[elem].to(u.km)/np.absolute(vel[elem])).value*u.s
        ca1 = ca[elem] + dca
        data = datas[elem] + dt

        print("off_ra: %s" % off_ra)
        print("off_de: %s" % off_de)
        print("ob_ra: %s" % ob_ra)
        print("ob_de: %s" % ob_de)
        print("st_off_ra: %s" % st_off_ra)
        print("dca: %s" % dca)
        print("dt: %s" % dt)
        print("ca1: %s" % ca1)
        print("data: %s" % data)

##### define parametros do mapa #####

        print("-------------- define parametros do mapa --------------")

        lon = stars[elem].ra - data.sidereal_time('mean', 'greenwich')
        center_map = EarthLocation(lon, stars[elem].dec)
        centert = True


        if 'centermap' in kwargs.keys():
            if not type(kwargs['centermap']) == EarthLocation:
                raise TypeError('centermap must be an Astropy EarthLocation Object')
            center_map = kwargs['centermap']
            centert = False
        fig = plt.figure(figsize=(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value))
        if not limits:
            m = Basemap(projection='ortho',lat_0=center_map.lat.value,lon_0=center_map.lon.value,resolution=resolution)
        elif np.array(limits).shape == (3,):
            if maplats:
                m = Basemap(projection='ortho',lat_0=center_map.lat.value,lon_0=center_map.lon.value,resolution=resolution)
                cx, cy = m(limits[1], limits[0])
                limits[0] = (cx - r)/1000.0
                limits[1] = (cy - r)/1000.0
            if np.any(np.absolute(limits[0:2]) > r):
                raise ValueError('Value for limits out of range (not in the map)')
            if mapsize[1] < mapsize[0]:
                ly = (limits[1]*u.km).to(u.m).value - r/limits[2]
                uy = (limits[1]*u.km).to(u.m).value + r/limits[2]
                lx = (limits[0]*u.km).to(u.m).value - (r/limits[2])*(mapsize[0]/mapsize[1])
                ux = (limits[0]*u.km).to(u.m).value + (r/limits[2])*(mapsize[0]/mapsize[1])
            else:
                lx = (limits[0]*u.km).to(u.m).value - r/limits[2]
                ux = (limits[0]*u.km).to(u.m).value + r/limits[2]
                ly = (limits[1]*u.km).to(u.m).value - (r/limits[2])*(mapsize[1]/mapsize[0])
                uy = (limits[1]*u.km).to(u.m).value + (r/limits[2])*(mapsize[1]/mapsize[0])
            m = Basemap(projection='ortho',lat_0=center_map.lat.value,lon_0=center_map.lon.value,resolution=resolution,llcrnrx=lx,llcrnry=ly,urcrnrx=ux,urcrnry=uy, area_thresh=2000)
            axf = fig.add_axes([-0.001,-0.001,1.002,1.002])
            axf.set_rasterization_zorder(1)
        else:
            raise ValueError('limits keyword must be an array with 3 elements: [centerx, centery, zoom]')
        if mapstyle == 1:
            m.drawmapboundary(fill_color='0.9')
            m.fillcontinents(color='1.0',lake_color='0.9')
            ptcolor= 'red'
            lncolor= 'blue'
            ercolor= 'blue'
            rncolor= 'blue'
            atcolor= 'blue'
            outcolor= 'red'
        elif mapstyle == 2:
            m.drawmapboundary(fill_color='aqua')
            m.fillcontinents(color='coral',lake_color='aqua')
            ptcolor= 'red'
            lncolor= 'blue'
            ercolor= 'red'
            rncolor= 'black'
            atcolor= 'black'
            outcolor= 'red'
        elif mapstyle == 3:
            m.shadedrelief()
            ptcolor= 'red'
            lncolor= 'blue'
            ercolor= 'red'
            rncolor= 'black'
            atcolor= 'black'
            outcolor= 'red'
        elif mapstyle == 4:
            m.bluemarble()
            ptcolor= 'red'
            lncolor= 'red'
            ercolor= 'red'
            rncolor= 'black'
            atcolor= 'black'
            outcolor= 'red'
        elif mapstyle == 5:
            m.etopo()
            ptcolor= 'red'
            lncolor= 'red'
            ercolor= 'red'
            rncolor= 'black'
            atcolor= 'black'
            outcolor= 'red'

        m.drawcoastlines(linewidth=0.5)  ## desenha as linhas da costa
        m.drawcountries(linewidth=0.5)  ## desenha os paises
        if 'states' in kwargs.keys():
            m.drawstates(linewidth=0.5)    ## Desenha os estados
        m.drawmeridians(np.arange(0,360,meridians))  ## desenha os meridianos
        m.drawparallels(np.arange(-90,90,parallels))  ## desenha os paralelos
        m.drawmapboundary()  ## desenha o contorno do mapa
        m.nightshade(data.datetime, alpha=0.25, zorder=1.2)  ## desenha a sombra da noite

        if 'ptcolor' in kwargs.keys():
            ptcolor = kwargs['ptcolor']
        if 'lncolor' in kwargs.keys():
            lncolor = kwargs['lncolor']
        if 'ercolor' in kwargs.keys():
            ercolor = kwargs['ercolor']
        if 'rncolor' in kwargs.keys():
            rncolor = kwargs['rncolor']
        if 'atcolor' in kwargs.keys():
            atcolor = kwargs['atcolor']
        if 'outcolor' in kwargs.keys():
            outcolor = kwargs['outcolor']

########### calcula caminho ##################
        print("-------------- calcula caminho --------------")

        vec = np.arange(0, int(8000/(np.absolute(vel[elem].value))), step)
        vec = np.sort(np.concatenate((vec,-vec[1:]), axis=0))
        pa = Angle(posa[elem])
        pa.wrap_at('180d', inplace=True)
        if pa > 90*u.deg:
            paplus = pa - 180*u.deg
        elif pa < -90*u.deg:
            paplus = pa + 180*u.deg
        else:
            paplus = pa
        deltatime = vec*u.s
        datas1 = data + TimeDelta(deltatime)
        datas1.delta_ut1_utc = 0
        longg = stars[elem].ra - datas1.sidereal_time('mean', 'greenwich')
        centers = EarthLocation(longg, stars[elem].dec, height=0.0*u.m)

        a = r*u.m
        b = r*u.m
        dista = (dist[elem].to(u.km)*ca1.to(u.rad)).value*u.km
        ax = a + dista*np.sin(pa) + (deltatime*vel[elem])*np.cos(paplus)
        by = b + dista*np.cos(pa) - (deltatime*vel[elem])*np.sin(paplus)
        ax2 = ax - (diam/2.0)*np.sin(paplus)
        by2 = by - (diam/2.0)*np.cos(paplus)
        ax3 = ax + (diam/2.0)*np.sin(paplus)
        by3 = by + (diam/2.0)*np.cos(paplus)

        lon1, lat1 = xy2latlon(ax2.value, by2.value, centers.lon.value, centers.lat.value)
        j = np.where(lon1 < 1e+30)
        xs, ys = m(lon1[j], lat1[j])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, color=lncolor)
        if centert:
            j = np.where(lon1 > 1e+30)
            m.plot(ax2[j].value, by2[j].value, color=outcolor, clip_on=False, zorder=-0.2)

        lon2, lat2 = xy2latlon(ax3.value, by3.value, centers.lon.value, centers.lat.value)
        j = np.where(lon2 < 1e+30)
        xt, yt = m(lon2[j], lat2[j])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, color=lncolor)
        if centert:
            j = np.where(lon2 > 1e+30)
            m.plot(ax3[j].value, by3[j].value, color=outcolor, clip_on=False, zorder=-0.2)

##### plot erro #####
        if erro:
            err = erro*u.mas
            errd = (dist[elem].to(u.km)*err.to(u.rad)).value*u.km
            ax2 = ax - errd*np.sin(paplus) - (diam/2.0)*np.sin(paplus)
            by2 = by - errd*np.cos(paplus) - (diam/2.0)*np.cos(paplus)
            ax3 = ax + errd*np.sin(paplus) + (diam/2.0)*np.sin(paplus)
            by3 = by + errd*np.cos(paplus) + (diam/2.0)*np.cos(paplus)
            lon1, lat1 = xy2latlon(ax2.value, by2.value, centers.lon.value, centers.lat.value)
            j = np.where(lon1 < 1e+30)
            xs, ys = m(lon1[j], lat1[j])
            xs = [i for i in xs if i < 1e+30]
            ys = [i for i in ys if i < 1e+30]
            m.plot(xs, ys, '--', color=ercolor)

            lon2, lat2 = xy2latlon(ax3.value, by3.value, centers.lon.value, centers.lat.value)
            j = np.where(lon2 < 1e+30)
            xt, yt = m(lon2[j], lat2[j])
            xt = [i for i in xt if i < 1e+30]
            yt = [i for i in yt if i < 1e+30]
            m.plot(xt, yt, '--', color=ercolor)

##### plot ring #####
        if ring:
            rng = ring*u.km
            ax2 = ax - rng*np.sin(paplus)
            by2 = by - rng*np.cos(paplus)
            ax3 = ax + rng*np.sin(paplus)
            by3 = by + rng*np.cos(paplus)
            lon1, lat1 = xy2latlon(ax2.value, by2.value, centers.lon.value, centers.lat.value)
            j = np.where(lon1 < 1e+30)
            xs, ys = m(lon1[j], lat1[j])
            xs = [i for i in xs if i < 1e+30]
            ys = [i for i in ys if i < 1e+30]
            m.plot(xs, ys, '--', color=rncolor)

            lon2, lat2 = xy2latlon(ax3.value, by3.value, centers.lon.value, centers.lat.value)
            j = np.where(lon2 < 1e+30)
            xt, yt = m(lon2[j], lat2[j])
            xt = [i for i in xt if i < 1e+30]
            yt = [i for i in yt if i < 1e+30]
            m.plot(xt, yt, '--', color=rncolor)

##### plot atm #####
        if atm:
            atmo = atm*u.km
            ax2 = ax - atmo*np.sin(paplus)
            by2 = by - atmo*np.cos(paplus)
            ax3 = ax + atmo*np.sin(paplus)
            by3 = by + atmo*np.cos(paplus)
            lon1, lat1 = xy2latlon(ax2.value, by2.value, centers.lon.value, centers.lat.value)
            j = np.where(lon1 < 1e+30)
            xs, ys = m(lon1[j], lat1[j])
            xs = [i for i in xs if i < 1e+30]
            ys = [i for i in ys if i < 1e+30]
            m.plot(xs, ys, color=atcolor)

            lon2, lat2 = xy2latlon(ax3.value, by3.value, centers.lon.value, centers.lat.value)
            j = np.where(lon2 < 1e+30)
            xt, yt = m(lon2[j], lat2[j])
            xt = [i for i in xt if i < 1e+30]
            yt = [i for i in yt if i < 1e+30]
            m.plot(xt, yt, '--', color=atcolor)

##### plot clat #####
        vec = np.arange(0, int(8000/(np.absolute(vel[elem].value))), cpoints)
        deltatime = np.sort(np.concatenate((vec,-vec[1:]), axis=0))*u.s
        axc = a + dista*np.sin(pa) + (deltatime*vel[elem])*np.cos(paplus)
        byc = b + dista*np.cos(pa) - (deltatime*vel[elem])*np.sin(paplus)
        if centert:
            m.plot(axc.value, byc.value, 'o', color=ptcolor, clip_on=False, markersize=mapsize[0].value*pscale*8.0/46.0, zorder=-0.2)

        datas2 = data + TimeDelta(deltatime)
        datas2.delta_ut1_utc = 0
        lon3 = stars[elem].ra - datas2.sidereal_time('mean', 'greenwich')
        clon1, clat1 = xy2latlon(axc.value, byc.value, lon3.value, stars[elem].dec.value)
        j = np.where(clon1 < 1e+30)
        xc, yc = m(clon1[j], clat1[j])
        xc = [i for i in xc if i < 1e+30]
        yc = [i for i in yc if i < 1e+30]
        m.plot(xc, yc, 'o', color=ptcolor, clip_on=False, markersize=mapsize[0].value*pscale*8.0/46.0)

#        xc, yc = m(lon.value, stars[elem].dec.value)
        if centert:
            m.plot(a + dista*np.sin(pa), b + dista*np.cos(pa), 'o', color=ptcolor, clip_on=False, markersize=mapsize[0].value*pscale*24.0/46.0)

######## Define o titulo e o label da saida #########
        title = 'Object        Diam   Tmax   dots <> ra_off_obj_de  ra_of_star_de\n{:10s} {:4.0f} km  {:5.1f}s  {:02d} s <>{:+6.1f} {:+6.1f}  {:+6.1f} {:+6.1f} \n'\
    .format(obj, diam.value, (diam/np.absolute(vel[elem])).value, cpoints, ob_ra.value, ob_de.value, st_off_ra.value, st_off_de.value)
        labelx = '\n year-m-d    h:m:s UT     ra__dec__J2000__candidate    C/A    P/A    vel   Delta   G*  long\n\
{}  {:02d} {:02d} {:07.4f} {:+03d} {:02d} {:06.3f} {:6.3f} {:6.2f} {:6.2f}  {:5.2f} {:5.1f}  {:3.0f}'.format(data.iso,
int(stars[elem].ra.hms.h), int(stars[elem].ra.hms.m), stars[elem].ra.hms.s, int(stars[elem].dec.dms.d), np.absolute(int(stars[elem].dec.dms.m)), np.absolute(stars[elem].dec.dms.s),
            ca1.value, posa[elem].value, vel[elem].value, dist[elem].value, magR[elem], longi[elem])

########### plota seta de direcao ##################
        print("--------- plota seta de direcao ---------")
        print("Limits: %s" % limits)
        if not limits:
            print(a+5500000*u.m,b-5500000*u.m, np.sin(paplus+90*u.deg)*np.sign(vel[elem]), np.cos(paplus+90*u.deg)*np.sign(vel[elem]))

            tmp_sin = np.sin(paplus+90*u.deg)*np.sign(vel[elem])
            tmp_cos = np.cos(paplus+90*u.deg)*np.sign(vel[elem])
            # plt.quiver(11870997,870997, 0.84395364, 0.53641612, width=0.005)
            plt.quiver(a+5500000*u.m,b-5500000*u.m, tmp_sin.value, tmp_cos.value, width=0.005)

            # plt.quiver(a+5500000*u.m,b-5500000*u.m, np.sin(paplus+90*u.deg)*np.sign(vel[elem]), np.cos(paplus+90*u.deg)*np.sign(vel[elem]), width=0.005)
        else:
            plt.quiver(a.value + lx + (ux-lx)*0.9,b.value + ly + (uy-ly)*0.1, np.sin(paplus+90*u.deg)*np.sign(vel[elem]), np.cos(paplus+90*u.deg)*np.sign(vel[elem]), width=0.005, zorder = 1.3)

####### imprime os nomes dos paises #####
        print("--------- imprime os nomes dos paises ---------")
        if os.path.isfile(country) == True:
            paises = np.loadtxt(country, dtype={'names': ('nome', 'lat', 'lon'), 'formats': ('S30', 'f8', 'f8')}, delimiter=',', ndmin=1)
            xpt,ypt = m(paises['lon'], paises['lat'])
            for i in np.arange(len(xpt)):
                plt.text(xpt[i],ypt[i],np.char.strip(paises['nome'][i]), weight='bold', color='grey', fontsize=30*cscale)

####### imprime os sitios ##############
        print("--------- imprime os sitios ---------")
        if os.path.isfile(sitearq) == True:
            sites = np.loadtxt(sitearq, ndmin=1,  dtype={'names': ('lat', 'lon', 'alt', 'nome', 'offx', 'offy', 'color'), 'formats': ('f8', 'f8', 'f8', 'S30',  'f8', 'f8', 'S30')}, delimiter=',')

            print(sites)

            xpt,ypt = m(sites['lon'],sites['lat'])
            sss = EarthLocation(sites['lon']*u.deg,sites['lat']*u.deg,sites['alt']*u.km)
            for i in np.arange(len(xpt)):
                m.plot(xpt[i],ypt[i],'o', markersize=mapsize[0].value*sscale*10.0/46.0, color=sites['color'][i].strip().decode('utf-8'))
                plt.text(xpt[i] + sites['offx'][i]*1000,ypt[i]+sites['offy'][i]*1000, sites['nome'][i].strip().decode('utf-8'), weight='bold', fontsize=25*nscale)

####### finaliza a plotagem do mapa#####
        print("--------- finaliza a plotagem do mapa ---------")

        plt.title(title, fontsize=mapsize[0].value*25/46, fontproperties='FreeMono', weight='bold')

        plt.xlabel(labelx, fontsize=mapsize[0].value*21/46, fontproperties='FreeMono', weight='bold')
        if 'nameimg' in kwargs.keys():
            nameimg = kwargs['nameimg']
        else:
            nameimg = '{}_{}'.format(obj, data.isot)

        print("nameimg: %s" % nameimg)
        print("fmt: %s" % fmt)
        print("dpi: %s" % dpi)

        plt.savefig('{}.{}'.format(nameimg, fmt), format=fmt, dpi=dpi)

        print('Gerado: {}.{}'.format(nameimg, fmt))
        plt.clf()
        plt.close()
Beispiel #40
0
def geramapa(delt):
    deltatime = delt*u.s
    datas1 = datas[idx] + TimeDelta(deltatime)
    datas1.delta_ut1_utc = 0
    lon = stars[idx].ra - datas1.sidereal_time('mean', 'greenwich')

    m = Basemap(projection='ortho',lat_0=stars[idx].dec.value,lon_0=lon.value,resolution=resolution)
#    m = Basemap(projection='ortho',lat_0=stars[idx].dec.value,lon_0=lon.value,resolution=resolution, llcrnrx=-7000000,llcrnry=-7000000,urcrnrx=7000000,urcrnry=7000000)
    m.drawcoastlines(linewidth=0.5)
    m.drawcountries(linewidth=0.5)
    m.drawstates(linewidth=0.5)
    m.drawmeridians(np.arange(0,360,30))
    m.drawparallels(np.arange(-90,90,30))
    m.drawmapboundary()
    ptcolor = 'black'
    lncolor = 'black'
    dscolor = 'black'
    if mapstyle == '2':
        m.drawmapboundary(fill_color='aqua')
        m.fillcontinents(color='coral',lake_color='aqua')
        ptcolor = 'red'
        lncolor = 'blue'
        dscolor = 'red'
    elif mapstyle == '3':
        m.shadedrelief()
        ptcolor = 'red'
        lncolor = 'blue'
        dscolor = 'red'
    elif mapstyle == '4':
        m.bluemarble()
        ptcolor = 'red'
        lncolor = 'red'
        dscolor = 'red'
    elif mapstyle == '5':
        m.etopo()
        ptcolor = 'red'
        lncolor = 'red'
        dscolor = 'red'
    if os.path.isfile(sitearq) == True:
        xpt,ypt = m(sites['lon'],sites['lat'])
        m.plot(xpt,ypt,'bo')
    CS=m.nightshade(datas1.datetime, alpha=0.2)
    a, b =m(lon.value, stars[idx].dec.value)
    a = a*u.m
    b = b*u.m
    dista = (dist[idx].to(u.km)*ca[idx].to(u.rad)).value*u.km
    disterr = (dist[idx].to(u.km)*erro.to(u.rad)).value*u.km
    ax = a + dista*np.sin(pa[idx]) + (deltatime*vel[idx])*np.cos(pa[idx])
    by = b + dista*np.cos(pa[idx]) - (deltatime*vel[idx])*np.sin(pa[idx])
    m.plot(ax,by, 'o', color=ptcolor, markersize=mapsize[0].value*20/46)
#    plt.legend(fontsize=mapsize[0].value*21/46)

    fig = plt.gcf()
    fig.set_size_inches(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value)
    plt.title('-{} D={}- dots each 60 s <> offsets (mas): obj=({:.1f},{:.1f}), star=({:.1f},{:.1f})\n'
        .format(obj, tamanho, ob_off_ra[idx].value, ob_off_de[idx].value, st_off_ra[idx].value, st_off_de[idx].value), fontsize=mapsize[0].value*25/46, fontproperties='FreeMono', weight='bold')
    plt.xlabel('\n year-m-d    h:m:s UT     ra__dec__J2000__candidate    C/A    P/A    vel   Delta   R*   K*  long\n\
{}  {:02d} {:02d} {:07.4f} {:+02d} {:02d} {:06.3f} {:6.3f} {:6.2f} {:6.2f}  {:5.2f} {:5.1f} {:4.1f}  {:3.0f}'
        .format(datas1.iso, int(stars[idx].ra.hms.h), int(stars[idx].ra.hms.m), stars[idx].ra.hms.s, int(stars[idx].dec.dms.d), np.absolute(int(stars[idx].dec.dms.m)), np.absolute(stars[idx].dec.dms.s),
        ca[idx].value, pa[idx].value, vel[idx].value, dist[idx].value, magR[idx], magK[idx], longi[idx]), fontsize=mapsize[0].value*21/46, fontproperties='FreeMono', weight='bold')
    plt.savefig('{}_{:05d}.png'.format(obj, np.where(g==delt)[0][0] + 1),dpi=100)
    print 'Gerado: {}_{:05d}.png'.format(obj, np.where(g==delt)[0][0] + 1)
    plt.clf()
Beispiel #41
0
def geramapa(idx):

    lons1, lats1, lons2, lats2, clon, clat, lab = calcfaixa(idx)
#    lon = stars[idx].ra - datas1.sidereal_time('mean', 'greenwich')
    center_map = EarthLocation('-77 02 28.3','38 49 19.1')
    fig = plt.figure(figsize=(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value))
    m = Basemap(projection='ortho',lat_0=center_map.latitude.value,lon_0=center_map.longitude.value,resolution=resolution,llcrnrx=-2000000.,llcrnry=-1500000.,urcrnrx=2000000.,urcrnry=1500000.)
#    m = Basemap(projection='ortho',lat_0=stars[idx].dec.value,lon_0=lon.value,resolution=resolution)
    ax = fig.add_axes([-0.003,-0.001,1.006,1.002])
    ax.set_rasterization_zorder(1)
    m.nightshade(datas.datetime, alpha=0.2, zorder=0.5)
    m.drawcoastlines(linewidth=0.5)
    m.drawcountries(linewidth=0.5)
    m.drawstates(linewidth=0.5)
    m.drawmeridians(np.arange(0,360,30))
    m.drawparallels(np.arange(-90,90,30))
    m.drawmapboundary()
    ptcolor = 'red'
    lncolor = 'black'
    dscolor = 'black'
    if mapstyle == '2':
        m.drawmapboundary(fill_color='aqua')
        m.fillcontinents(color='coral',lake_color='aqua')
        ptcolor = 'red'
        lncolor = 'blue'
        dscolor = 'red'
    elif mapstyle == '3':
        m.shadedrelief()
        ptcolor = 'red'
        lncolor = 'blue'
        dscolor = 'red'
    elif mapstyle == '4':
        m.bluemarble()
        ptcolor = 'red'
        lncolor = 'red'
        dscolor = 'red'
    elif mapstyle == '5':
        m.etopo()
        ptcolor = 'red'
        lncolor = 'red'
        dscolor = 'red'
    a, b =m(center_map.longitude.value, center_map.latitude.value)
    a = a*u.m
    b = b*u.m
#    dista = (dist[idx].to(u.km)*ca[idx].to(u.rad)).value*u.km
#    disterr = (dist[idx].to(u.km)*erro.to(u.rad)).value*u.km
#    vec = np.arange(0,7000,(np.absolute(vel)*(30*u.s)).value)*u.km + np.absolute(vel)*(30*u.s)
#    vec = np.concatenate((vec.value,-vec.value), axis=0)*u.km
#    ax = a + dista*np.sin(pa[idx])
#    ax2 = ax + vec*np.cos(pa[idx])
#    ax3 = ax2 - tamanho/2*np.sin(pa[idx])
#    ax4 = ax2 + tamanho/2*np.sin(pa[idx])
#    ax5 = a + (dista-disterr)*np.sin(pa[idx]) + vec*np.cos(pa[idx])
#    ax6 = a + (dista+disterr)*np.sin(pa[idx]) + vec*np.cos(pa[idx])
#    by = b + dista*np.cos(pa[idx])
#    by2 = by - vec*np.sin(pa[idx])
#    by3 = by2 - tamanho/2*np.cos(pa[idx])
#    by4 = by2 + tamanho/2*np.cos(pa[idx])
#    by5 = b + (dista-disterr)*np.cos(pa[idx]) - vec*np.sin(pa[idx])
#    by6 = b + (dista+disterr)*np.cos(pa[idx]) - vec*np.sin(pa[idx])
    xs, ys = m(lons1, lats1)
    xs = [i for i in xs if i < 1e+30]
    ys = [i for i in ys if i < 1e+30]
    m.plot(xs, ys, 'b')
    xt, yt = m(lons2, lats2)
    xt = [i for i in xt if i < 1e+30]
    yt = [i for i in yt if i < 1e+30]
    m.plot(xt, yt, 'b')
    xc, yc = m(clon, clat)
    labe = [lab[i] for i in np.arange(len(lab)) if xc[i] < 1e+30]
    xc = [i for i in xc if i < 1e+30]
    yc = [i for i in yc if i < 1e+30]
    m.plot(xc, yc, 'or')

#    m.plot(ax,by, 'o', color=ptcolor, markersize=int(mapsize[0].value*20/46))
#    m.plot(ax2.to(u.m),by2.to(u.m), 'o', color=ptcolor, markersize=int(mapsize[0].value*12/46))
#    m.plot(ax3.to(u.m), by3.to(u.m), color=lncolor)
#    m.plot(ax4.to(u.m), by4.to(u.m), color=lncolor)
    m.quiver(a-0*u.m,b-600000*u.m, 20, 0, width=0.005)

#    ax2 = a + dista*np.sin(pa) + [(i - datas).sec for i in temposplot]*u.s*vel*np.cos(paplus)
#    by2 = b + dista*np.cos(pa) - [(i - datas).sec for i in temposplot]*u.s*vel*np.sin(paplus)
#
#    labels = [i.iso.split()[1][0:8] for i in temposplot]
#    m.plot(ax2, by2, 'ro')
    
    for label, axpt, bypt in zip(labe, xc, yc):
        ax.text(axpt + 0, bypt + 350000, label, rotation=60, weight='bold')


    if os.path.isfile(sitearq) == True:
        xpt,ypt = m(sites['lon'],sites['lat'])
        m.plot(xpt,ypt,'bo')
        offset = [[xpt[0] + 100000,xpt[0] + 100000,xpt[0] + 100000,xpt[3] + 400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000],[10000,-30000,-60000,70000,30000,-20000,-70000,-30000,-70000]]
        for i in np.arange(len(xpt)):
            ax.text(offset[0][i],ypt[i]+offset[1][i],sites['nome'][i], weight='bold')

#    m.plot(ax5.to(u.m), by5.to(u.m), '--', color=dscolor, label='+-{} error'.format(erro))
#    m.plot(ax6.to(u.m), by6.to(u.m), '--', color=dscolor)
#    plt.legend(fontsize=mapsize[0].value*21/46)

    fig = plt.gcf()
    fig.set_size_inches(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value)
#    plt.title('Objeto       Diam   dots <>  ra_off_obj_de  ra_of_star_de\n{:10s} {:4.0f} km  60 s <> {:+6.1f} {:+6.1f}  {:+6.1f} {:+6.1f} \n'
#        .format(obj, tamanho.value, ob_off_ra[idx].value, ob_off_de[idx].value, st_off_ra[idx].value, st_off_de[idx].value), fontsize=mapsize[0].value*25/46, fontproperties='FreeMono', weight='bold')
#    plt.xlabel('\n year-m-d    h:m:s UT     ra__dec__J2000__candidate    C/A    P/A    vel   Delta   R*   K*  long\n\
#{}  {:02d} {:02d} {:07.4f} {:+02d} {:02d} {:06.3f} {:6.3f} {:6.2f} {:6.2f}  {:5.2f} {:5.1f} {:4.1f}  {:3.0f}'
#        .format(datas[idx].iso, int(stars[idx].ra.hms.h), int(stars[idx].ra.hms.m), stars[idx].ra.hms.s, int(stars[idx].dec.dms.d), np.absolute(int(stars[idx].dec.dms.m)), np.absolute(stars[idx].dec.dms.s),
#        ca[idx].value, pa[idx].value, vel[idx].value, dist[idx].value, magR[idx], magK[idx], longi[idx]), fontsize=mapsize[0].value*21/46, fontproperties='FreeMono', weight='bold')
    plt.savefig('{}_{}.eps'.format(obj, datas.isot), format='eps', dpi=300)
    print 'Gerado: {}_{}.eps'.format(obj, datas.isot)
    plt.clf()
Beispiel #42
0
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from datetime import datetime

map = Basemap(projection='vandg',lon_0=0,resolution='c')

map.drawmapboundary(fill_color="#7777ff")
map.fillcontinents(color="#ddaa66",lake_color="#7777ff")

map.drawcoastlines()

map.nightshade(datetime.now(), delta=0.2)

plt.show()
class ISSData():
  Arrays=[]
  rows = 0
  n = 0
  step = 1104
  Headers = []
  Directory = ''
  normPath = ""
  chatty = False
  map = ""
  ag =""
  
  def __init__(self,fileName,directory=""):
      """ Check to see if files exists 
      """
      self.map = Basemap(projection='mill',lon_0=-10)
      normPath = os.path.normpath(directory+fileName)
      try:
          dFile= open(normPath,"r")
      except:
          print "Cannot open", normPath
      # save tested path for later use
      self.normPath = normPath
      dFile.close()  
      
   
  def readDataFromFile(self):
    NL=0
    with open(self.normPath) as file:
      for line in file:
        line= line.rstrip()
        NL +=1
        ns = line.split(",")
        if (NL==1):
          headers= ns
          for h in headers:
              self.Headers.append(h)   
          self.Headers.pop(-1) # remove time stamp header as time is not a float
          for val in ns:
            empty=[]
            self.Arrays.append(empty)  
        else:
          nv = 0
          for val in ns:
            self.Arrays[nv].append(val)
            nv +=1
    file.close()
    self.rows = len(self.Arrays[0])

    nh=0
    print " File", self.normPath, "  rows=", self.rows, self.rows/360, "hours"
    print self.Arrays[19][0]," - ", self.Arrays[19][-1]
    print " Measurement      #    min         max        median      average    stddev"
    for h in self.Headers:
        narray = np.array(self.Arrays[nh]).astype(np.float32)
        if (nh == 0):
        # each data point is 10 secs so this scales x axis to minutes
            narray = narray / 6.0
        #Calculate some basic stats on each row
 
        max = np.amax(narray)
        if (headers[nh] == "pitch") or (headers[nh] == "yaw") :
            if (max >= 20000.):
                # convert from radians to degrees?
                # in the first Spacecraft dataset only (I think)
                narray = narray / 57.3
            nv=0
            for val in narray:
              if (val <= -180.0):
                narray[nv] = narray[nv] + 360.0
              elif (val >= 180.0):
                 narray[nv] = narray[nv] - 360.0
              nv +=1
              # pitch looks better when normalized about zero 
            max = np.amax(narray)
        min = np.amin(narray)
        med = np.median(narray)
        aver = np.average(narray)
        stddev = np.std(narray)
        print "%12s %6s %10.5f %10.5f %10.5f %10.5f %10.5f" % (h, nh, min,max, med, aver, stddev)
        self.Arrays[nh] = narray
        nh +=1
    # Normalize 


  def printStats(self,param=1,n=0,step=1104):
        print step,"datapoints - ", (self.Arrays[19][n])," - ", \
        (self.Arrays[19][n+step])
        print " Measurement      #    min         max        median      average    stddev"
        min = np.amin(self.Arrays[param][n:n+step])
        max = np.amax(self.Arrays[param][n:n+step])
        med = np.median(self.Arrays[param][n:n+step])
        aver = np.average(self.Arrays[param][n:n+step])
        stddev = np.std(self.Arrays[param][n:n+step])
        print "%12s %6s %10.5f %10.5f %10.5f %10.5f %10.5f" % ( self.Headers[param], param, min,max, med, aver, stddev)

  def drawNightDay(self,param=1,n=0,step=1104):
        if (self.chatty): print self.Headers[param], n,step
        cn = int(n + step /2)
        ct = self.Arrays[19][cn]
        print "Centre time period = ", ct
        # miller projection
        
        # plot coastlines, draw label meridians and parallels.
        self.map.drawcoastlines()
        self.map.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0])
        self.map.drawmeridians(np.arange(self.map.lonmin,self.map.lonmax+30,60),labels=[0,0,0,1])
        # fill continents 'coral' (with zorder=0), color wet areas 'aqua'
        self.map.drawmapboundary(fill_color='white')
        self.map.fillcontinents(color='coral',lake_color='white')
        # shade the night areas, with alpha transparency so the
        # map shows through. Use current time in UTC.
        #en = el.findIndexFromDate(ct)
        #eo = el.extractISSfromIndex(en)
        #print eo
        date = el.findDateFromString(ct)
        if (step <= 1104):
            self.map.nightshade(date)
        else: print "Track too long for night shading"
        plt.title('ISS Track %s (UTC)' % ct)
#        self.drawIssTrack(elements,param,n,step)
        
        
  def drawIssTrack(self,elements,param=1,n=0,step=1104):
      st = self.Arrays[19][n]
      et = self.Arrays[19][n+step]
      print "Plotting from - ", st, " to ", et
      cn = int(n + step /2)
      ct = self.Arrays[19][cn]
      line1,line2=elements.elemsFromDateString(ct)
      if (self.chatty): print "drawIssTrack", n,step, ct, line1, line2
      for nn in range(n,n+step,6):
          ntime = self.Arrays[19][nn]
          #if self.chatty: print ntime
          tle_rec = ephem.readtle("ISS", line1, line2)
          tle_rec.compute(ntime)
          #convert to strings#
          lat2string = str(tle_rec.sublat)
          long2string = str(tle_rec.sublong)
          lati = lat2string.split(":")
          longt = long2string.split(":")
          #if self.chatty: print "ISS SUBSURFACE -", lati,longt
          lat = float(lati[0]) + float(lati[1])/60. + float(lati[2])/3600.
          lon = float(longt[0]) + float(longt[1])/60. + float(longt[2])/3600. 
          xpt,ypt=self.map(lon,lat)
	  # drawing style
	  kargs = "g+"
          if (nn == n):
              plt.text(xpt,ypt,"start")
          if (nn >= (n+step -6) ):
              plt.text(xpt,ypt,"end")
	  # make every 5 mins dot
	  if ((nn % 30) == 0): kargs = "g." 
          self.map.plot(xpt,ypt,kargs)
       
        
  def drawDataPlot(self,param=1,n=0,step=1104):
      plt.figure(1)
      plt.clf()
      plt.title(self.Headers[param])
      plt.plot(self.Arrays[0][n:(n+step)],self.Arrays[param][n:(n+step)])
      #self.ag.set_xdata(self.Arrays[0][n:(n+step)])
      plt.draw()
Beispiel #44
0
def plot_simulated_data(ivm, filename=None):

    import matplotlib
    import matplotlib.pyplot as plt
    import matplotlib.gridspec as gridspec
    from matplotlib.collections import LineCollection
    from mpl_toolkits.basemap import Basemap

    if filename is None:
        out_fname = './summary_orbit_simulated_data.png'
    else:
        out_fname = filename

    # make monotonically increasing longitude signal
    diff = ivm['glong'].diff()

    idx, = np.where(diff < 0.)
    for item in idx:
        ivm[item:, 'glong'] += 360.

    f = plt.figure(figsize=(8.5, 7))

    time1 = ivm.data.index[0].strftime('%Y-%h-%d %H:%M:%S')
    if ivm.data.index[0].date() == ivm.data.index[-1].date():
        time2 = ivm.data.index[-1].strftime('%H:%M:%S')
    else:
        time2 = ivm.data.index[-1].strftime('%Y-%h-%d %H:%M:%S')
    # Overall Plot Title
    plt.suptitle(''.join(('SPORT IVM ', time1, ' -- ', time2)), fontsize=18)

    # create grid for plots
    gs = gridspec.GridSpec(5, 2, width_ratios=[12, 1])

    ax = f.add_subplot(gs[0, 0])
    plt.plot(np.log10(ivm['ion_dens']), 'k', label='total')
    plt.plot(np.log10(ivm['ion_dens'] * ivm['frac_dens_o']), 'r', label='O+')
    plt.plot(np.log10(ivm['ion_dens'] * ivm['frac_dens_h']), 'b', label='H+')
    # plt.plot(np.log10(ivm['ion_dens']*ivm['frac_dens_he']), 'g', label='He+')
    plt.legend(loc=(01.01, 0.15))
    ax.set_title('Log Ion Density')
    ax.set_ylabel('Log Density (N/cc)')
    ax.set_ylim([1., 6.])
    ax.axes.get_xaxis().set_visible(False)

    ax2 = f.add_subplot(gs[1, 0], sharex=ax)
    plt.plot(ivm['ion_temp'])
    plt.legend(loc=(1.01, 0.15))
    ax2.set_title('Ion Temperature')
    ax2.set_ylabel('Temp (K)')
    ax2.set_ylim([500., 1500.])
    ax2.axes.get_xaxis().set_visible(False)

    # determine altitudes greater than 770 km
    # idx, = np.where(ivm['alt'] > 770.)

    ax3 = f.add_subplot(gs[2, 0], sharex=ax)
    plt.plot(ivm['sim_wind_sc_x'], color='b', linestyle='--')
    plt.plot(ivm['sim_wind_sc_y'], color='r', linestyle='--')
    plt.plot(ivm['sim_wind_sc_z'], color='g', linestyle='--')
    ax3.set_title('Neutral Winds in S/C X, Y, and Z')
    ax3.set_ylabel('Velocity (m/s)')
    ax3.set_ylim([-200., 200.])
    ax3.axes.get_xaxis().set_visible(False)
    plt.legend(loc=(1.01, 0.15))
    ax3.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%H:%M'))
    # # xlabels = [label[0:6] for label in xlabels]
    # plt.setp(ax3.xaxis.get_majorticklabels(), rotation=20, ha='right')

    ax4 = f.add_subplot(gs[3, 0], sharex=ax)
    plt.plot(ivm['B_sc_x'] * 1e5, color='b', linestyle='--')
    plt.plot(ivm['B_sc_y'] * 1e5, color='r', linestyle='--')
    plt.plot(ivm['B_sc_z'] * 1e5, color='g', linestyle='--')
    ax4.set_title('Magnetic Field in S/C X, Y, and Z')
    ax4.set_ylabel('Gauss')
    ax4.set_ylim([-3.5, 3.5])
    # ax3.axes.get_xaxis().set_visible(False)
    plt.legend(loc=(1.01, 0.15))
    ax4.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%H:%M'))
    # # xlabels = [label[0:6] for label in xlabels]
    plt.setp(ax4.xaxis.get_majorticklabels(), rotation=20, ha='right')

    # ivm info
    ax6 = f.add_subplot(gs[4, 0])

    # do world plot if time to be plotted is less than 285 minutes, less than 3 orbits
    time_diff = ivm.data.index[-1] - ivm.data.index[0]
    if time_diff > pds.Timedelta(minutes=285):
        #    # do long time plot
        ivm['glat'].plot(label='glat')  #legend=True, label='mlat')
        ivm['mlt'].plot(label='mlt')  #legend=True, label='mlt')
        plt.title('Satellite Position')
        plt.legend(['mlat', 'mlt'], loc=(1.01, 0.15))
    #    ivm['glong'].plot(secondary_y = True, label='glong')#legend=True, secondary_y = True, label='glong')

    else:

        # make map the same size as the other plots
        s1pos = plt.get(ax, 'position').bounds
        s6pos = plt.get(ax6, 'position').bounds
        ax6.set_position([s1pos[0], s6pos[1] + .008, s1pos[2], s1pos[3]])

        #fix longitude range for plot. Pad longitude so that first sample aligned with
        #ivm measurement sample
        lon0 = ivm[0, 'glong']
        lon1 = ivm[-1, 'glong']
        # print (lon0, lon1)

        # enforce minimal longitude window, keep graphics from being too disturbed
        if (lon1 - lon0) < 90:
            lon0 -= 45.
            lon1 += 45.
        if lon1 > 720:
            lon0 -= 360.
            lon1 -= 360.
            ivm[:, 'glong'] -= 360.
        # print (lon0, lon1)

        m=Basemap(projection='mill', llcrnrlat=-60, urcrnrlat=60., urcrnrlon=lon1.copy(), \
        llcrnrlon=lon0.copy(), resolution='c', ax=ax6, fix_aspect=False)
        # m is an object which manages drawing to the map
        # it also acts as a transformation function for geo coords to plotting coords

        # coastlines
        m.drawcoastlines(ax=ax6)
        # get first longitude meridian to plot
        plon = np.ceil(lon0 / 60.) * 60.
        m.drawmeridians(np.arange(plon, plon + 360. - 22.5, 60),
                        labels=[0, 0, 0, 1],
                        ax=ax6)
        m.drawparallels(np.arange(-20, 20, 20))
        # time midway through ivm to plot terminator locations
        midDate = ivm.data.index[len(ivm.data.index) // 2]

        # plot day/night terminators
        try:
            cs = m.nightshade(midDate)
        except ValueError:
            pass

        x, y = m(ivm['glong'].values, ivm['glat'].values)
        points = np.array([x, y]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        plot_norm = plt.Normalize(300, 500)
        try:
            plot_cmap = plt.get_cmap('viridis')
        except:
            plot_cmap = plt.get_cmap('jet')

        lc = LineCollection(segments,
                            cmap=plot_cmap,
                            norm=plot_norm,
                            linewidths=5.0)
        lc.set_array(ivm['alt'].values)
        sm = plt.cm.ScalarMappable(cmap=plot_cmap, norm=plot_norm)
        sm._A = []

        ax6.add_collection(lc)

        ax6_bar = f.add_subplot(gs[4, 1])
        #plt.colorbar(sm)
        cbar = plt.colorbar(cax=ax6_bar,
                            ax=ax6,
                            mappable=sm,
                            orientation='vertical',
                            ticks=[300., 400., 500.])
        plt.xlabel('Altitude')
        plt.ylabel('km')

    f.tight_layout()
    # buffer for overall title
    f.subplots_adjust(bottom=0.06, top=0.91, right=.91)
    plt.subplots_adjust(hspace=.44)

    plt.savefig(out_fname)

    return
Beispiel #45
0
def plot_burst_map(fig,
                   gps_data,
                   show_terminator=True,
                   plot_trajectory=True,
                   show_transmitters=True,
                   TLE_file=None,
                   print_GPS_entries=True,
                   TX_file='resources/nb_transmitters.conf'):

    logger = logging.getLogger()

    m_ax = fig.add_subplot(1, 1, 1)

    m = Basemap(projection='mill',
                lon_0=0,
                ax=m_ax,
                llcrnrlon=-180,
                llcrnrlat=-70,
                urcrnrlon=180,
                urcrnrlat=70)

    lats = [x['lat'] for x in gps_data]
    lons = [x['lon'] for x in gps_data]
    T_gps = np.array([x['timestamp'] for x in gps_data])

    sx, sy = m(lons, lats)

    m.drawcoastlines(color='k', linewidth=1, ax=m_ax)
    m.drawparallels(np.arange(-90, 90, 30), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(m.lonmin, m.lonmax + 30, 60),
                    labels=[0, 0, 1, 0])
    m.drawmapboundary(fill_color='cyan')
    m.fillcontinents(color='white', lake_color='cyan')

    if show_terminator:
        try:
            # Find the median timestamp to use:
            avg_ts = np.mean(
                [k['timestamp'] for k in gps_data if k['time_status'] > 20])

            CS = m.nightshade(datetime.datetime.utcfromtimestamp(avg_ts))
        except:
            logger.warning('Problem plotting day/night terminator')

    if plot_trajectory:
        try:
            if TLE_file:
                try:
                    with open(TLE_file, 'r') as file:
                        TLE = file.read().split('\n')
                        logger.info(f'loaded TLE file {TLE_file}')
                except:
                    logger.warning(f'failed to load TLE file {TLE_file}')
            else:
                logger.info('using default TLE')
                # A default TLE, from mid-may 2020.
                TLE = [
                    "1 45120U 19071K   20153.15274580 +.00003602 +00000-0 +11934-3 0  9995",
                    "2 45120 051.6427 081.8638 0012101 357.8092 002.2835 15.33909680018511"
                ]

            avg_ts = np.mean(
                [k['timestamp'] for k in gps_data if k['time_status'] > 20])
            t_mid = datetime.datetime.utcfromtimestamp(avg_ts)
            t1 = t_mid - datetime.timedelta(minutes=15)
            t2 = t_mid + datetime.timedelta(minutes=15)

            traj, tvec = compute_ground_track(
                TLE, t1, t2, tstep=datetime.timedelta(seconds=10))

            tlats = traj[:, 1]
            tlons = traj[:, 0]
            simtime = [
                x.replace(tzinfo=datetime.timezone.utc).timestamp()
                for x in tvec
            ]

            mid_ind = np.argmin(np.abs(np.array(tvec) - t_mid))
            zx, zy = m(tlons, tlats)
            z = m.scatter(zx,
                          zy,
                          c=simtime,
                          marker='.',
                          s=10,
                          alpha=0.5,
                          cmap=get_cmap('plasma'),
                          zorder=100,
                          label='TLE')

            z2 = m.scatter(zx[mid_ind],
                           zy[mid_ind],
                           edgecolor='k',
                           marker='*',
                           s=50,
                           zorder=101,
                           label='Center (TLE)')
        except:
            logger.warning('Problem plotting ground track from TLE')

    if show_transmitters:
        try:
            call_sign_config = ConfigParser()
            try:
                fp = open(TX_file)
                call_sign_config.read_file(fp)
                fp.close()
            except:
                logger.warning('failed to load transmitters file')

            for tx_name, vals in call_sign_config.items('NB_Transmitters'):
                vv = vals.split(',')
                tx_freq = float(vv[0])
                tx_lat = float(vv[1])
                tx_lon = float(vv[2])
                px, py = m(tx_lon, tx_lat)
                p = m.scatter(px, py, marker='p', s=20, color='r', zorder=99)
                name_str = '{:s}  \n{:0.1f}  '.format(tx_name.upper(),
                                                      tx_freq / 1000)
                m_ax.text(px,
                          py,
                          name_str,
                          fontsize=8,
                          fontweight='bold',
                          ha='left',
                          va='bottom',
                          color='k',
                          label='TX')
            p.set_label('TX')
            s = m.scatter(sx,
                          sy,
                          c=T_gps,
                          marker='o',
                          s=20,
                          cmap=get_cmap('plasma'),
                          zorder=100,
                          label='GPS')
        except:
            logger.warning('Problem plotting narrowband transmitters')
    m_ax.legend()

    if print_GPS_entries:
        gstr = ''
        for entry in gps_data:
            time = datetime.datetime.strftime(
                datetime.datetime.utcfromtimestamp(entry['timestamp']),
                '%D %H:%M:%S')
            tloc = entry['time_status'] > 20
            ploc = entry['solution_status'] == 0
            gstr += '{:s} ({:1.2f}, {:1.2f}): time lock: {:b} position lock: {:b}\n'.format(
                time, entry['lat'], entry['lon'], tloc, ploc)

        fig.text(.5, 0, gstr, ha='center', va='bottom')

    fig.tight_layout()
Beispiel #46
0
def geramapa(star, data, title, labelx, nameimg, mapstyle='1', resolution='l', centermap=None, lats=None, erro=None, ring=None, atm=None, clat=None, sitearq=None, fmt='png', dpi=100, mapsize=None, cpoints=60, off=0):
    lon = star.ra - data.sidereal_time('mean', 'greenwich')
    center_map = EarthLocation(lon.value, star.dec.value)
    if not centermap == None:
        center_map = EarthLocation(centermap[0],centermap[1])
    m = Basemap(projection='ortho',lat_0=center_map.latitude.value,lon_0=center_map.longitude.value,resolution=resolution)
#    m = Basemap(projection='ortho',lat_0=center_map.latitude.value,lon_0=center_map.longitude.value,resolution=resolution,llcrnrx=-2000000.,llcrnry=-1500000.,urcrnrx=2000000.,urcrnry=1500000.)
#    kx = fig.add_axes([-0.003,-0.001,1.006,1.002])
#    kx.set_rasterization_zorder(1)
    m.nightshade(data.datetime, alpha=0.3, zorder=0.5)  ## desenha a sombra da noite
    m.drawcoastlines(linewidth=0.5)  ## desenha as linhas da costa
    m.drawcountries(linewidth=0.5)  ## desenha os paises
    m.drawstates(linewidth=0.5)    ## Desenha os estados
    m.drawmeridians(np.arange(0,360,30))  ## desenha os meridianos
    m.drawparallels(np.arange(-90,90,30))  ## desenha os paralelos
    m.drawmapboundary()  ## desenha o contorno do mapa
    style = {'1': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'blue', 'rncolor':'blue', 'atcolor':'blue', 'outcolor':'red'},
             '2': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'},
             '3': {'ptcolor': 'red', 'lncolor': 'blue', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'},
             '4': {'ptcolor': 'red', 'lncolor': 'red', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'},
             '5': {'ptcolor': 'red', 'lncolor': 'red', 'ercolor':'red', 'rncolor':'black', 'atcolor':'black', 'outcolor':'red'}}
    if mapstyle == '2':
        m.drawmapboundary(fill_color='aqua')
        m.fillcontinents(color='coral',lake_color='aqua')
    elif mapstyle == '3':
        m.shadedrelief()
    elif mapstyle == '4':
        m.bluemarble()
    elif mapstyle == '5':
        m.etopo()
    if not lats == None:
        xs, ys = m(lats[0], lats[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, color=style[mapstyle]['lncolor'])
        xt, yt = m(lats[2], lats[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, color=style[mapstyle]['lncolor'])
        m.plot(lats[4], lats[5], color=style[mapstyle]['outcolor'], clip_on=False, zorder=-0.2)
        m.plot(lats[6], lats[7], color=style[mapstyle]['outcolor'], clip_on=False, zorder=-0.2)
#    else:
#        m.plot(lats[4], lats[5], color=style[mapstyle]['outcolor'], clip_on=False, zorder=0.2)
#        m.plot(lats[6], lats[7], color=style[mapstyle]['outcolor'], clip_on=False, zorder=0.2)
    if not erro == None:
        xs, ys = m(erro[0], erro[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, '--', color=style[mapstyle]['ercolor'])
        xt, yt = m(erro[2], erro[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, '--', color=style[mapstyle]['ercolor'])
    if not ring == None:
        xs, ys = m(ring[0], ring[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, '--', color=style[mapstyle]['rncolor'])
        xt, yt = m(ring[2], ring[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, '--', color=style[mapstyle]['rncolor'])
    if not atm == None:
        xs, ys = m(atm[0], atm[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, color=style[mapstyle]['atcolor'])
        xt, yt = m(atm[2], atm[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, color=style[mapstyle]['atcolor'])
    if not clat == None:
        xc, yc, lab = [], [], []
        cp = Time(clat[5], format='iso')
        vec = np.arange(0, (cp[-1] - data).sec, cpoints)
        vec = np.sort(np.concatenate((vec,-vec[1:]), axis=0))*u.s
        for i in vec:
            g = data + TimeDelta(i) + TimeDelta(off*u.s)
            if g.iso in clat[2]:
                a = np.where(np.array(clat[2]) == g.iso)
                x, y = m(np.array(clat[0])[a], np.array(clat[1])[a])
                xc.append(x)
                yc.append(y)
                lab.append(g.iso.split()[1][0:8])
            elif g.iso in clat[5]:
                a = np.where(np.array(clat[5]) == g.iso)
                xc.append(np.array(clat[3])[a])
                yc.append(np.array(clat[4])[a])
                lab.append(g.iso.split()[1][0:8])
            else:
                if len(clat[2]) == 0:
                    a = [0]
                else:
                    co = Time(clat[2], format='iso')
                    a = np.argsort(np.absolute(co - g))[0:2]
                if 0 not in a and len(co)-1 not in a:
                    b = np.absolute((co[a] - g).sec)
                    x, y = m(np.array(clat[0])[a], np.array(clat[1])[a])
                    xc.append(np.sum(x*(1/b))/np.sum(1/b))
                    yc.append(np.sum(y*(1/b))/np.sum(1/b))
                    lab.append(g.iso.split()[1][0:8])
                else:
                    co = Time(clat[5], format='iso')
                    a = np.argsort(np.absolute(co - g))[0:2]
                    b = np.absolute((co[a] - g).sec)
                    xc.append(np.sum(np.array(clat[3])[a]*(1/b))/np.sum(1/b))
                    yc.append(np.sum(np.array(clat[4])[a]*(1/b))/np.sum(1/b))
                    lab.append(g.iso.split()[1][0:8])
        m.plot(xc, yc, 'o', color=style[mapstyle]['ptcolor'], clip_on=False, markersize=mapsize[0].value*8/46)
        m.plot(clat[6][0], clat[6][1], 'o', color=style[mapstyle]['ptcolor'], clip_on=False, markersize=mapsize[0].value*20/46)

#    for label, axpt, bypt in zip(lab, xc, yc):
#        plt.text(axpt + 0, bypt + 350000, label, rotation=60, weight='bold')




#    m.plot(ax,by, 'o', color=ptcolor, markersize=int(mapsize[0].value*20/46))
#    m.plot(ax2.to(u.m),by2.to(u.m), 'o', color=ptcolor, markersize=int(mapsize[0].value*12/46))
#    m.plot(ax3.to(u.m), by3.to(u.m), color='red')
#    m.plot(ax4.to(u.m), by4.to(u.m), color='red')
#    m.quiver(a-0*u.m,b-600000*u.m, 20, 0, width=0.005)

#    ax2 = a + dista*np.sin(pa) + [(i - datas).sec for i in temposplot]*u.s*vel*np.cos(paplus)
#    by2 = b + dista*np.cos(pa) - [(i - datas).sec for i in temposplot]*u.s*vel*np.sin(paplus)
#
#    labels = [i.iso.split()[1][0:8] for i in temposplot]
#    m.plot(ax2, by2, 'ro')

#    if os.path.isfile(sitearq) == True:
#        xpt,ypt = m(sites['lon'],sites['lat'])
#        m.plot(xpt,ypt,'bo')
#        offset = [[xpt[0] + 100000,xpt[0] + 100000,xpt[0] + 100000,xpt[3] + 400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000],[10000,-30000,-60000,70000,30000,-20000,-70000,-30000,-70000]]
#        for i in np.arange(len(xpt)):
#            ax.text(offset[0][i],ypt[i]+offset[1][i],sites['nome'][i], weight='bold')

#    m.plot(ax5.to(u.m), by5.to(u.m), '--', color=dscolor, label='+-{} error'.format(erro))
#    m.plot(ax6.to(u.m), by6.to(u.m), '--', color=dscolor)
#    plt.legend(fontsize=mapsize[0].value*21/46)



    fig = plt.gcf()
    fig.set_size_inches(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value)
    plt.title(title, fontsize=mapsize[0].value*25/46, fontproperties='FreeMono', weight='bold')
    plt.xlabel(labelx, fontsize=mapsize[0].value*21/46, fontproperties='FreeMono', weight='bold')
    plt.savefig('{}.{}'.format(nameimg, fmt), format=fmt, dpi=dpi)
    print 'Gerado: {}.{}'.format(nameimg, fmt)
    plt.clf()
Beispiel #47
0
def plot_flux_basemap(flux, in_lats, in_lons, flashes=None, plottime=None,
                      logscale=False, clims=[0,1], num_contours=10, mode='counts'):

    lons, lats = np.meshgrid(in_lons, in_lats)

    # print np.shape(lons)
    # print np.shape(lats)

    new_coords = transform_coords(lats.ravel(), lons.ravel(),
                 100*np.ones_like(lons.ravel()),'geomagnetic','geographic')

    mag_lons = new_coords[:,1].T.reshape(np.shape(lons))
    mag_lats = new_coords[:,0].T.reshape(np.shape(lats))

    # print np.shape(mag_lons)
    # print np.shape(mag_lats)


    fig = plt.figure()
    ax1 = plt.subplot(111)
    m = Basemap(ax1,resolution='c',projection='robin', lon_0 = 0)
    x, y = m(mag_lons, mag_lats)

    # CS1 = m.contourf(x,y,flux,cmap=plt.cm.jet,extend='both')


    m.drawcoastlines(color='white')
    m.drawmapboundary()
    m.fillcontinents(color='grey',alpha=0.3)
    if plottime is not None:
        if isinstance(plottime,str):
            plottime = datetime.datetime.strptime(plottime,'%Y-%m-%dT%H:%M:%S')

        m.nightshade(plottime, alpha=0.25)


    contours = np.linspace(clims[0],clims[1],num_contours+1)

    # log scale?
    if logscale:
        pd = np.log10(flux).ravel()
    else:
        pd = flux.ravel()
    
    # Clip flux to min and max contours
    pd = np.clip(pd, contours[0], contours[-1])

    # Plot flux
    CS1 = plt.tricontourf(x.ravel(),y.ravel(),pd, contours,cmap=plt.cm.jet)
    cbar = m.colorbar(CS1, size="2%", pad=0.5)

    if logscale:
        ctix = np.arange(clims[0], clims[1]+1)
#         print ctix
        cbar.set_ticks(ctix)
        cbar.set_ticklabels(['$10^{%d}$'%f for f in ctix])


    # if logscale:
    #     logstr = 'log$_{10}$'
    # else:
    #     logstr=''

    if mode == 'energy':
        cbar.set_label('Energy flux [mErg/cm$^2$ sec]')
    elif mode == 'counts':
        cbar.set_label('Particle flux [el/cm$^2$ sec]')


    if flashes is not None:
        new_flash_coords= transform_coords(flashes[:,0], flashes[:,1], 
                           100*np.ones_like(flashes[:,0]), 'geomagnetic','geographic')



        xf, yf = m(new_flash_coords[:,1], new_flash_coords[:,0])
        msize = abs(flashes[:,2])*2
        mcolor= flashes[:,3]
        p2  = m.scatter(xf, yf, marker='o', c=mcolor,s=msize,alpha=0.8,edgecolor='None', cmap=plt.cm.Reds_r)
        # divider = make_axes_locatable(ax1)
        # cax2 = divider.append_axes("bottom",size="2%",pad=0.5)
        # plt.colorbar(p2, cax=cax2)

    ax1.set_title(plottime)
    plt.tight_layout()
    #plt.subplots_adjust(0,0,1,1,0,0)
    return fig