def test_exception_maxalt(): with pytest.raises(ValueError): aacgmv2.convert(60, 0, 2001, dtObj) with pytest.raises(ValueError): aacgmv2.convert(60, 0, [300, 2001], dtObj) # the following should not raise exceptions aacgmv2.convert(60, 0, 2001, dtObj, trace=True) aacgmv2.convert(60, 0, 2001, dtObj, allowtrace=True) aacgmv2.convert(60, 0, 2001, dtObj, badidea=True)
def f4(): plt.figure(figsize=(6.88,6.74)) #geographic coordinates ax1, projection1 = gcc.create_map( 2, 2, 1, 'pol', 90, 50, 0, coastlines=False,useLT=True, dlat=10, lonticklabel=(1, 1, 1, 1)) ax1.plot([45,45],[50,90], 'k--',transform=ccrs.PlateCarree()) ax1.plot([225,225],[50,90], 'k--',transform=ccrs.PlateCarree()) ax1.plot([105,105],[50,90], 'k--',transform=ccrs.PlateCarree()) ax1.plot([285,285],[50,90], 'k--',transform=ccrs.PlateCarree()) ax1.scatter( 0, 90, color='r', transform=ccrs.PlateCarree(), zorder=10, label='North Pole') ax1.text(0,1,'(a)', transform = plt.gca().transAxes) plt.legend(loc=[0.5,1.1]) ax2, projection2 = gcc.create_map( 2, 2, 2, 'pol', -50, -90, 0, coastlines=False,useLT=True, dlat=10, lonticklabel=(1, 1, 1, 1)) ax2.scatter( 0, -90, color='b', transform=ccrs.PlateCarree(),label='South Pole') ax2.text(0,1,'(b)', transform = plt.gca().transAxes) plt.legend(loc=[-0.1,1.1]) #geomagnetic coordinates ax3, projection3 = gcc.create_map( 2, 2, 3, 'pol', 90, 50, 0, coastlines=False,useLT=True, dlat=10, lonticklabel=(1, 1, 1, 1)) mlatn,mlonn = convert(90,0,0,date=dt.date(2002,3,21)) for k in range(24): mltn = convert_mlt(mlonn[0],dtime=dt.datetime(2003,3,21,k)) ax3.scatter(mltn*15,mlatn[0],color='r',transform=ccrs.PlateCarree()) ax3.scatter(180,75,s=50,c='k',marker='x',transform=ccrs.PlateCarree()) ax3.text(0,1,'(c)', transform = plt.gca().transAxes) ax4, projection4 = gcc.create_map( 2, 2, 4, 'pol', -50, -90, 0, coastlines=False,useLT=True, dlat=10, lonticklabel=(1, 1, 1, 1)) mlats,mlons = convert(-90,0,0,date=dt.date(2002,3,21)) for k in range(24): mlts = convert_mlt(mlons[0],dtime=dt.datetime(2003,3,21,k)) ax4.scatter(mlts*15,mlats[0],color='b',transform=ccrs.PlateCarree()) ax4.scatter(180,-75,s=50,c='k',marker='x',transform=ccrs.PlateCarree()) ax4.text(0,1,'(d)', transform = plt.gca().transAxes) plt.savefig( '/Users/guod/Documents/Pole_Density_MLT_Change/Figures/' '000_Pole_Feature.pdf') return
def test_convert_list(self): """Test conversion for list input""" self.lat, self.lon = aacgmv2.convert([60], [0], [300], self.dtime) assert isinstance(self.lat, np.ndarray) assert isinstance(self.lon, np.ndarray) assert self.lat.shape == self.lon.shape and self.lat.shape == (1, ) np.testing.assert_allclose(self.lat, [58.2258], rtol=1e-4) np.testing.assert_allclose(self.lon, [81.1685], rtol=1e-4) self.lat, self.lon = aacgmv2.convert([60, 61], [0, 0], [300, 300], self.dtime) assert isinstance(self.lat, np.ndarray) assert isinstance(self.lon, np.ndarray) assert self.lat.shape == self.lon.shape and self.lat.shape == (2, ) np.testing.assert_allclose(self.lat, [58.2258, 59.3186], rtol=1e-4) np.testing.assert_allclose(self.lon, [81.1685, 81.6140], rtol=1e-4)
def test_convert_location_failure(self): """Test conversion with a bad location""" self.lat, self.lon = aacgmv2.convert([0], [0], [0], self.dtime) assert isinstance(self.lat, np.ndarray) assert isinstance(self.lon, np.ndarray) assert self.lat.shape == self.lon.shape and self.lat.shape == (1, ) assert np.all([np.isnan(self.lat), np.isnan(self.lon)])
def test_convert_single_val(self): """Test conversion for a single value""" self.lat, self.lon = aacgmv2.convert(60, 0, 300, self.dtime) assert isinstance(self.lat, np.ndarray) assert isinstance(self.lon, np.ndarray) assert self.lat.shape == self.lon.shape and self.lat.shape == (1, ) np.testing.assert_allclose(self.lat, [58.2258], rtol=1e-4) np.testing.assert_allclose(self.lon, [81.1685], rtol=1e-4)
def test_convert_arr_single(self): """Test conversion for array input with one element""" self.lat, self.lon = aacgmv2.convert(np.array([60]), np.array([0]), np.array([300]), self.dtime) assert isinstance(self.lat, np.ndarray) assert isinstance(self.lon, np.ndarray) assert self.lat.shape == self.lon.shape and self.lat.shape == (1, ) np.testing.assert_allclose(self.lat, [58.2258], rtol=1e-4) np.testing.assert_allclose(self.lon, [81.1685], rtol=1e-4)
def test_convert_arr_mix(self): """Test conversion for an array and floats""" self.lat, self.lon = aacgmv2.convert(np.array([60, 61]), 0, 300, self.dtime) assert isinstance(self.lat, np.ndarray) assert isinstance(self.lon, np.ndarray) assert self.lat.shape == self.lon.shape and self.lat.shape == (2, ) np.testing.assert_allclose(self.lat, [58.2258, 59.3186], rtol=1e-4) np.testing.assert_allclose(self.lon, [81.1685, 81.6140], rtol=1e-4)
def test_warning_below_ground_convert(self): """ Test that a warning is issued if altitude is below zero""" import logbook lwarn = u"conversion not intended for altitudes < 0 km" with logbook.TestHandler() as handler: self.lat, self.lon = aacgmv2.convert([60], [0], [-1], self.dtime) assert handler.has_warning(lwarn) handler.close()
def get_flight_route(i,does_this_route_pass_through_arctic,airport_code,dest_airports): ### returns a pandas dataframe with the flight route info ### or returns None if the flight does not pass through the Arctic if not does_this_route_pass_through_arctic[i]: return None folderpath = 'gis_temp/' layername = airport_code+'-'+dest_airports.loc[i].code mag_lat = [dest_airports.loc[i].code+' mag lat']; mag_lon = [dest_airports.loc[i].code+' mag lon'] gc_lat = [dest_airports.loc[i].code+' lat']; gc_lon = [dest_airports.loc[i].code+' lon'] with open(folderpath+'/'+layername+'.geojson') as json_file: data = json.load(json_file) if len(data['features'][0]['geometry']['coordinates'][0]) == 2: #if everything is working as expected for j in range(len(data['features'][0]['geometry']['coordinates'][:])): lon,lat = data['features'][0]['geometry']['coordinates'][j] mg_lat,mg_lon = aacgmv2.convert(lat, lon, 10, date=date.today(), a2g=False, trace=False, allowtrace=False, badidea=False, geocentric=False) mag_lat.append(mg_lat[0]) mag_lon.append(mg_lon[0]) gc_lat.append(lat) gc_lon.append(lon) else: #anti-meridian crossing, they split the results into two groups so the len will be a lot longer for j in range(len(data['features'][0]['geometry']['coordinates'][0][:])): lon,lat = data['features'][0]['geometry']['coordinates'][0][j] mg_lat,mg_lon = aacgmv2.convert(lat, lon, 10, date=date.today(), a2g=False, trace=False, allowtrace=False, badidea=False, geocentric=False) mag_lat.append(mg_lat[0]) mag_lon.append(mg_lon[0]) gc_lat.append(lat) gc_lon.append(lon) for j in range(len(data['features'][0]['geometry']['coordinates'][1][:])): lon,lat = data['features'][0]['geometry']['coordinates'][1][j] mg_lat,mg_lon = aacgmv2.convert(lat, lon, 10, date=date.today(), a2g=False, trace=False, allowtrace=False, badidea=False, geocentric=False) mag_lat.append(mg_lat[0]) mag_lon.append(mg_lon[0]) gc_lat.append(lat) gc_lon.append(lon) df = pd.DataFrame.from_records([gc_lat,gc_lon,mag_lat,mag_lon]) return df
def test_convert_result_values_shape(): lat, lon = aacgmv2.convert(np.array([[60, 61, 62], [63, 64, 65]]), 0, 300, dtObj) aacgmv2._aacgmv2.setDateTime(*date) assert (lat[0, 0], lon[0, 0], 1) == aacgmv2._aacgmv2.aacgmConvert(60, 0, 300, G2A) assert (lat[0, 1], lon[0, 1], 1) == aacgmv2._aacgmv2.aacgmConvert(61, 0, 300, G2A) assert (lat[0, 2], lon[0, 2], 1) == aacgmv2._aacgmv2.aacgmConvert(62, 0, 300, G2A) assert (lat[1, 0], lon[1, 0], 1) == aacgmv2._aacgmv2.aacgmConvert(63, 0, 300, G2A) assert (lat[1, 1], lon[1, 1], 1) == aacgmv2._aacgmv2.aacgmConvert(64, 0, 300, G2A) assert (lat[1, 2], lon[1, 2], 1) == aacgmv2._aacgmv2.aacgmConvert(65, 0, 300, G2A)
def solar_conductance(self, dt, mlats, mlts, return_f107=False): """ Estimate the solar conductance using methods from: Cousins, E. D. P., T. Matsuo, and A. D. Richmond (2015), Mapping high-latitude ionospheric electrodynamics with SuperDARN and AMPERE --which cites-- Asgeir Brekke, Joran Moen, Observations of high latitude ionospheric conductances Maybe is not good for SZA for southern hemisphere? Don't know Going to use absolute value of latitude because that's what's done in Cousins IDL code. """ # Find the closest hourly f107 value # to the current time to specifiy the conductance f107 = ovation_utilities.get_daily_f107(dt) if hasattr(self, '_f107'): log.warning( ('Warning: Overriding real F107 {0}'.format(f107) + 'with secret instance property _f107 {0}'.format(self._f107) + 'this is for debugging and will not' + 'produce accurate results for a particular date.')) f107 = self._f107 # print "F10.7 = %f" % (f107) # Convert from magnetic to geocentric using the AACGMv2 python library flatmlats, flatmlts = mlats.flatten(), mlts.flatten() flatmlons = aacgmv2.convert_mlt(flatmlts, dt, m2a=True) try: glats, glons = aacgmv2.convert(flatmlats, flatmlons, 110. * np.ones_like(flatmlats), date=dt, a2g=True, geocentric=False) except AttributeError: # convert method was deprecated glats, glons, r = aacgmv2.convert_latlon_arr(flatmlats, flatmlons, 110., dt, method_code='A2G') sigp, sigh = brekke_moen_solar_conductance(dt, glats, glons, f107) sigp_unflat = sigp.reshape(mlats.shape) sigh_unflat = sigh.reshape(mlats.shape) if return_f107: return sigp_unflat, sigh_unflat, f107 else: return sigp_unflat, sigh_unflat
def test_output_type(): lat, lon = aacgmv2.convert(60, 0, 300, dtObj) print(type(lat)) print(lat.shape) print(lat.size) assert isinstance(lat, np.ndarray) assert isinstance(lon, np.ndarray) lat, lon = aacgmv2.convert([60], [0], [300], dtObj) assert isinstance(lat, np.ndarray) assert isinstance(lon, np.ndarray) lat, lon = aacgmv2.convert([60, 61], [0, 0], [300, 300], dtObj) assert isinstance(lat, np.ndarray) assert isinstance(lon, np.ndarray) lat, lon = aacgmv2.convert([60, 61, 62], 0, 300, dtObj) assert isinstance(lat, np.ndarray) assert isinstance(lon, np.ndarray) lat, lon = aacgmv2.convert(np.array([60, 61, 62]), 0, 300, dtObj) assert isinstance(lat, np.ndarray) assert isinstance(lon, np.ndarray) lat, lon = aacgmv2.convert(np.array([[60, 61, 62], [63, 64, 65]]), 0, 300, dtObj) assert isinstance(lat, np.ndarray) assert isinstance(lon, np.ndarray)
def test_convert_mult_array_mix(self): """Test conversion for a multi-dim array and floats""" self.lat, self.lon = aacgmv2.convert( np.array([[60, 61, 62], [63, 64, 65]]), 0, 300, self.dtime) assert isinstance(self.lat, np.ndarray) assert isinstance(self.lon, np.ndarray) assert self.lat.shape == self.lon.shape and self.lat.shape == (2, 3) np.testing.assert_allclose( self.lat, [[58.2258, 59.3186, 60.4040], [61.4820, 62.5528, 63.6164]], rtol=1e-4) np.testing.assert_allclose( self.lon, [[81.1685, 81.6140, 82.0872], [82.5909, 83.1286, 83.7039]], rtol=1e-4)
def test_output_shape_size(): lat, lon = aacgmv2.convert(60, 0, 300, dtObj) assert lat.shape == tuple() assert lon.shape == tuple() assert lat.size == 1 assert lon.size == 1 lat, lon = aacgmv2.convert([60], [0], [300], dtObj) assert lat.shape == (1,) assert lon.shape == (1,) assert lat.size == 1 assert lon.size == 1 lat, lon = aacgmv2.convert([60, 61], [0, 0], [300, 300], dtObj) assert lat.shape == (2,) assert lon.shape == (2,) assert lat.size == 2 assert lon.size == 2 lat, lon = aacgmv2.convert([60, 61, 62], 0, 300, dtObj) assert lat.shape == (3,) assert lon.shape == (3,) assert lat.size == 3 assert lon.size == 3 lat, lon = aacgmv2.convert(np.array([60, 61, 62]), 0, 300, dtObj) assert lat.shape == (3,) assert lon.shape == (3,) assert lat.size == 3 assert lon.size == 3 lat, lon = aacgmv2.convert(np.array([[60, 61, 62], [63, 64, 65]]), 0, 300, dtObj) assert lat.shape == (2, 3) assert lon.shape == (2, 3) assert lat.size == 6 assert lon.size == 6
def test_convert_result_values_badidea(): lat, lon = aacgmv2.convert(60, 0, [300, 5000], dtObj, badidea=True) aacgmv2._aacgmv2.setDateTime(*date) assert (lat[0], lon[0], 1) == aacgmv2._aacgmv2.aacgmConvert(60, 0, 300, BADIDEA) assert (lat[1], lon[1], 1) == aacgmv2._aacgmv2.aacgmConvert(60, 0, 5000, BADIDEA)
def test_convert_result_values_geocentric(): lat_p, lon_p = aacgmv2.convert(60, 0, 300, dtObj, geocentric=True) aacgmv2._aacgmv2.setDateTime(*date) lat_c, lon_c, _ = aacgmv2._aacgmv2.aacgmConvert(60, 0, 300, GEOCENTRIC) assert lat_p == lat_c assert lon_p == lon_c
def test_convert_result_values_A2G_trace(): lat_p, lon_p = aacgmv2.convert(60, 0, 300, dtObj, a2g=True, trace=True) aacgmv2._aacgmv2.setDateTime(*date) lat_c, lon_c, _ = aacgmv2._aacgmv2.aacgmConvert(60, 0, 300, A2G | TRACE) assert lat_p == lat_c assert lon_p == lon_c
def test_convert_result_values_allowtrace(): lat, lon = aacgmv2.convert(60, 0, [300, 5000], dtObj, allowtrace=True) aacgmv2._aacgmv2.setDateTime(*date) assert (lat[0], lon[0], 1) == aacgmv2._aacgmv2.aacgmConvert(60, 0, 300, ALLOWTRACE) assert (lat[1], lon[1], 1) == aacgmv2._aacgmv2.aacgmConvert(60, 0, 5000, ALLOWTRACE)
def figure2_3(run=1): plt.close('all') plt.figure(figsize=(8.28, 9.25)) if run==1: g = g1 else: g = g2 rholevels = [np.linspace(8, 16, 21)*1e-10, np.linspace(1,4,21)*1e-11, np.linspace(0.5, 8,21)*1e-13] rhoticks = [np.arange(8, 17, 2)*1e-10, np.arange(1,5,1)*1e-11, np.arange(1, 9, 2)*1e-13] templevels = [np.linspace(600, 800, 21), np.linspace(900,1500,21), np.linspace(900, 1500,21)] tempticks = [np.arange(600, 900, 100), np.arange(900,1600,200), np.arange(900, 1600, 200)] labels =[('(a)','(b)','(c)'), ('(d)','(e)','(f)'), ('(g)','(h)','(i)')] qlat, qlon = convert(-90, 0, 0, date=dt.date(2003,3,22), a2g=True) for ialt, alt in enumerate([150, 300, 600]): alt_ind = np.argmin(np.abs(g['Altitude'][0, 0, 2:-2]/1000-alt))+2 alt_str = '%6.0f' % (g['Altitude'][0, 0, alt_ind]/1000) ax, projection = gcc.create_map( 3, 3, ialt+1, 'polar', nlat=nlat, slat=slat, dlat=10, centrallon=g3ca.calculate_centrallon(g, 'polar', useLT=True), coastlines=False, lonticklabel=[1,1,1,1]) # density lon0, lat0, zdata0 = g3ca.contour_data('Rho', g, alt=alt) fp = (lat0[:,0]>slat) & (lat0[:,0]<nlat) lon0, lat0, zdata0 = lon0[fp, :], lat0[fp,:], zdata0[fp,:] hc = ax.contourf( lon0, lat0, zdata0, rholevels[ialt], transform=ccrs.PlateCarree(), cmap='jet', extend='both') gcapos = ax.get_position() axcb = [ gcapos.x0, gcapos.y0+0.028, gcapos.width, gcapos.height/20] axcb = plt.axes(axcb) hcb = plt.colorbar( hc, cax=axcb, extendrect=True, ticks=rhoticks[ialt], orientation='horizontal') # wind lon0, lat0, ewind, nwind = g3ca.vector_data(g, 'neutral', alt=alt) lon0, lat0, ewind, nwind = g3ca.convert_vector( lon0, lat0, ewind, nwind, plot_type='polar', projection=projection) hq = ax.quiver( lon0, lat0, ewind, nwind, scale=1000, scale_units='inches', regrid_shape=20) ax.quiverkey(hq, 0.97, 0.92, 500, '500 m/s') ax.scatter(qlon, qlat, color='k', transform=ccrs.PlateCarree()) ax.scatter( 0, -90, color='w', s=30, transform=ccrs.PlateCarree(), zorder=1000) ax.set_title('%s km' % alt_str, y=1.08) if ialt == 0: plt.text( -0.2, 0.5, r'$\rho$ and wind', rotation=90, transform=ax.transAxes, verticalalignment='center') plt.text(0, 0.9, labels[0][ialt],transform=ax.transAxes,color='r') #---------------------------------------------------------------------- ax, projection = gcc.create_map( 3, 3, ialt+4, 'polar', nlat=nlat, slat=slat, dlat=10, centrallon=g3ca.calculate_centrallon(g, 'polar', useLT=True), coastlines=False, lonticklabel=[1,1,1,1]) # temperature lon0, lat0, zdata0 = g3ca.contour_data('Temperature', g, alt=alt) fp = (lat0[:,0]>slat) & (lat0[:,0]<nlat) lon0, lat0, zdata0 = lon0[fp, :], lat0[fp,:], zdata0[fp,:] hc = ax.contourf( lon0, lat0, zdata0, templevels[ialt], transform=ccrs.PlateCarree(), cmap='jet', extend='both') gcapos = ax.get_position() axcb = [ gcapos.x0, gcapos.y0-0.017, gcapos.width, gcapos.height/20] axcb = plt.axes(axcb) hcb = plt.colorbar( hc, cax=axcb, extendrect=True, ticks=tempticks[ialt], orientation='horizontal') ax.scatter(qlon, qlat, color='k', transform=ccrs.PlateCarree()) ax.scatter( 0, -90, color='w', s=30, transform=ccrs.PlateCarree(), zorder=1000) if ialt == 0: plt.text( -0.2, 0.5, 'Temperature (K)', rotation=90, transform=ax.transAxes, verticalalignment='center') plt.text(0, 0.9, labels[1][ialt],transform=ax.transAxes,color='r') #---------------------------------------------------------------------- ax, projection = gcc.create_map( 3, 3, ialt+7, 'polar', nlat=nlat, slat=slat, dlat=10, centrallon=g3ca.calculate_centrallon(g, 'polar', useLT=True), coastlines=False, lonticklabel=[1,1,1,1]) # ion drift lon0, lat0, ewind, nwind = g3ca.vector_data(g, 'ion', alt=alt) lon0, lat0, ewind, nwind = g3ca.convert_vector( lon0, lat0, ewind, nwind, plot_type='polar', projection=projection) if run == 2: ewind, nwind = 0.1*ewind, 0.1*nwind hq = ax.quiver( lon0, lat0, ewind, nwind, scale=1000, scale_units='inches', regrid_shape=20) ax.quiverkey(hq, 0.97, 0.92, 500, '500 m/s') ax.scatter(qlon, qlat, color='k', transform=ccrs.PlateCarree()) ax.scatter( 0, -90, color='w', s=30, transform=ccrs.PlateCarree(), zorder=1000) if ialt == 0: plt.text( -0.2, 0.5, 'Ion Drift', rotation=90, transform=ax.transAxes, verticalalignment='center') plt.text(0, 0.9, labels[2][ialt],transform=ax.transAxes,color='r') plt.subplots_adjust(wspace=0.25, hspace=0.25, top=0.95, bottom=0.05) if run==1: plt.savefig(savepath+'Figure2.eps') plt.savefig(savepath+'Figure2.jpeg') else: plt.savefig(savepath+'Figure3.eps') plt.savefig(savepath+'Figure3.jpeg') return
def figure5_7(alt=150): times = pd.to_datetime([ '2003-03-22 00:00:00', '2003-03-22 00:30:00', '2003-03-22 01:00:00', '2003-03-22 02:00:00', '2003-03-22 03:00:00', '2003-03-22 06:00:00']) plt.close('all') plt.figure(figsize=(9.5, 9.25)) xtitle = [ r'$-\nabla\cdot w$', r'$-\nabla\cdot u$', r'$-\frac{w\cdot\nabla\rho}{\rho}$', r'$-\frac{u\cdot\nabla\rho}{\rho}$', r'$\frac{\partial \rho}{\rho\partial t}$', r'$\delta\rho$ (%)'] ylabel = times.strftime('%H:%M') qlat, qlon = convert(-90, 0, 0, date=dt.date(2003,3,22), a2g=True) for itime, time in enumerate(times): strtime = time.strftime('%y%m%d_%H%M') fn1 = glob.glob( '/home/guod/simulation_output/momentum_analysis/'\ 'run_no_shrink_iondrift_4_1/data/3DALL_t%s*.bin' % strtime) fn2 = glob.glob( '/home/guod/simulation_output/momentum_analysis/'\ 'run_shrink_iondrift_4_c1/data/3DALL_t%s*.bin' % strtime) g1 = gitm.read(fn1[0]) g2 = gitm.read(fn2[0]) lon1 = g1['Longitude'] lat1 = g1['Latitude'] alt1 = g1['Altitude'] Re = 6371*1000 # Earth radius, unit: m RR = Re+alt1 omega = 2*pi/(24*3600) rho1 = np.array(g1['Rho']) nwind1 = g1['V!Dn!N (north)'] ewind1 = g1['V!Dn!N (east)'] + omega*RR*np.cos(lat1) uwind1 = g1['V!Dn!N (up)'] div_rhov1 = \ (cr.calc_div_hozt(lon1, lat1, alt1, rho1*nwind1, rho1*ewind1)\ +cr.calc_div_vert(alt1, rho1*uwind1))/rho1 vert_divv1 = cr.calc_div_vert(alt1, uwind1) hozt_divv1 = cr.calc_div_hozt(lon1, lat1, alt1, nwind1, ewind1) vert_vgradrho1 = uwind1*cr.calc_rusanov_alts_ausm(alt1,rho1)/rho1 hozt_vgradrho1 = \ (nwind1*cr.calc_rusanov_lats(lat1,alt1,rho1)\ +ewind1*cr.calc_rusanov_lons(lon1,lat1,alt1,rho1))/rho1 dc1 = [ vert_divv1, hozt_divv1, vert_vgradrho1, hozt_vgradrho1, div_rhov1, rho1] lon2 = g2['Longitude'] lat2 = g2['Latitude'] alt2 = g2['Altitude'] Re = 6371*1000 # Earth radius, unit: m RR = Re+alt2 omega = 2*pi/(24*3600) rho2 = g2['Rho'] nwind2 = g2['V!Dn!N (north)'] ewind2 = g2['V!Dn!N (east)'] + omega*RR*np.cos(lat2) uwind2 = g2['V!Dn!N (up)'] div_rhov2 = \ (cr.calc_div_hozt(lon2, lat2, alt2, rho2*nwind2, rho2*ewind2)\ +cr.calc_div_vert(alt2, rho2*uwind2))/rho2 vert_divv2 = cr.calc_div_vert(alt2, uwind2) hozt_divv2 = cr.calc_div_hozt(lon2, lat2, alt2, nwind2, ewind2) vert_vgradrho2 = uwind2*cr.calc_rusanov_alts_ausm(alt2,rho2)/rho2 hozt_vgradrho2 = \ (nwind2*cr.calc_rusanov_lats(lat2,alt2,rho2)\ +ewind2*cr.calc_rusanov_lons(lon2,lat2,alt2,rho2))/rho2 dc2 = [ vert_divv2, hozt_divv2, vert_vgradrho2, hozt_vgradrho2, div_rhov2, rho2] alt_ind = np.argmin(np.abs(alt1[0, 0, :]/1000-alt)) alt_str = '%6.0f' % (alt1[0, 0, alt_ind]/1000) for idc in range(6): lonticklabel = [0, 0, 0, 0] if idc == 0: lonticklabel[3] = lonticklabel[-1]+1 if idc == 5: lonticklabel[1] = lonticklabel[-1]+1 if itime == 0: lonticklabel[0] = lonticklabel[-2]+1 if itime == 5: lonticklabel[2] = lonticklabel[-2]+1 ax, projection = gcc.create_map( 6, 6, itime*6+idc+1, 'polar', nlat=nlat, slat=slat, dlat=10, centrallon=g3ca.calculate_centrallon(g1, 'polar', useLT=True), coastlines=False, lonticklabel=lonticklabel) g1['temp'] = -(dc1[idc] - dc2[idc]) if idc==5: g1['temp'] = 100*(dc1[idc] - dc2[idc])/dc2[idc] lon0, lat0, zdata0 = g3ca.contour_data('temp', g1, alt=alt) fp = (lat0[:,0]>slat) & (lat0[:,0]<nlat) lon0, lat0, zdata0 = lon0[fp, :], lat0[fp,:], zdata0[fp,:] levels = np.linspace(-8,8,21)*1e-5 if idc==5: levels = np.linspace(-30,30,21) hc = ax.contourf( lon0, lat0, zdata0, levels, transform=ccrs.PlateCarree(), cmap='seismic', extend='both') # wind difference alt_ind = np.argmin(np.abs(alt1[0, 0, :]/1000-alt)) alt_str = '%6.0f' % (alt1[0, 0, alt_ind]/1000) lon1, lat1, ewind1, nwind1 = g3ca.vector_data( g1, 'neutral', alt=alt) lon2, lat2, ewind2, nwind2 = g3ca.vector_data( g2, 'neutral', alt=alt) lon0, lat0 = lon1, lat1 lon0, lat0, ewind0, nwind0 = g3ca.convert_vector( lon0, lat0, ewind1-ewind2, nwind1-nwind2, plot_type='polar', projection=projection) hq = ax.quiver( lon0, lat0, ewind0, nwind0, scale=1500, scale_units='inches', regrid_shape=20, headwidth=5) ax.scatter( qlon, qlat, s=10, color='k', transform=ccrs.PlateCarree()) ax.scatter( 0, -90, color='w', s=10, transform=ccrs.PlateCarree(), zorder=1000) if idc==0: plt.text( -0.3, 0.5, ylabel[itime], rotation=90, transform=ax.transAxes, verticalalignment='center') if itime==0: plt.title(xtitle[idc], y=1.15, fontsize=14) texts = ['(a)', '(b)', '(c)', '(d)', '(e)', '(f)'] plt.text(0.05,1,texts[idc],transform=plt.gca().transAxes, color='r') if itime==5: axp = ax.get_position() cax = [axp.x0, axp.y0-0.03, axp.x1-axp.x0, 1/20*(axp.y1-axp.y0)] cax = plt.axes(cax) ticks = np.arange(-8e-5, 8.1e-5, 4e-5) if idc<5 else \ np.arange(-30, 31, 15) hcb = plt.colorbar( hc, cax=cax, extendrect=True, orientation='horizontal', ticks=ticks) if idc<5: hcb.formatter.set_powerlimits((0,0)) hcb.update_ticks() plt.subplots_adjust(wspace=0, hspace=0) if alt==300: plt.savefig(savepath+'Figure5.eps') plt.savefig(savepath+'Figure5.jpeg') if alt==600: plt.savefig(savepath+'Figure7.eps') plt.savefig(savepath+'Figure7.jpeg') return
def geo2mag(lat, lon, alt): #Latitudes range from -90 to 90. #Longitudes range from -180 to 180. (Maybe, who knows -- http://ccmc.gsfc.nasa.gov/requests/instant/ranges.php #Verified with http://ccmc.gsfc.nasa.gov/requests/instant/instant1.php?model=AACGM&type=1 mlat, mlon = convert(lat, lon, alt, None) return mlat
def test_exception_lat90(): with pytest.raises(ValueError): aacgmv2.convert(91, 0, 300, dtObj) with pytest.raises(ValueError): aacgmv2.convert(-91, 0, 300, dtObj) with pytest.raises(ValueError): aacgmv2.convert([60, 91], 0, 300, dtObj) with pytest.raises(ValueError): aacgmv2.convert([60, -91], 0, 300, dtObj) # the following should not raise exceptions aacgmv2.convert(90, 0, 300, dtObj) aacgmv2.convert(-90, 0, 300, dtObj)
def f4(): plt.figure(figsize=(6.88, 6.74)) #geographic coordinates ax1, projection1 = gcc.create_map(2, 2, 1, 'pol', 90, 50, 0, coastlines=False, useLT=True, dlat=10, lonticklabel=(1, 1, 1, 1)) ax1.plot([45, 45], [50, 90], 'k--', transform=ccrs.PlateCarree()) ax1.plot([225, 225], [50, 90], 'k--', transform=ccrs.PlateCarree()) ax1.plot([105, 105], [50, 90], 'k--', transform=ccrs.PlateCarree()) ax1.plot([285, 285], [50, 90], 'k--', transform=ccrs.PlateCarree()) ax1.scatter(0, 90, color='r', transform=ccrs.PlateCarree(), zorder=10, label='North Pole') ax1.text(0, 1, '(a)', transform=plt.gca().transAxes) plt.legend(loc=[0.5, 1.1]) ax2, projection2 = gcc.create_map(2, 2, 2, 'pol', -50, -90, 0, coastlines=False, useLT=True, dlat=10, lonticklabel=(1, 1, 1, 1)) ax2.scatter(0, -90, color='b', transform=ccrs.PlateCarree(), label='South Pole') ax2.text(0, 1, '(b)', transform=plt.gca().transAxes) plt.legend(loc=[-0.1, 1.1]) #geomagnetic coordinates ax3, projection3 = gcc.create_map(2, 2, 3, 'pol', 90, 50, 0, coastlines=False, useLT=True, dlat=10, lonticklabel=(1, 1, 1, 1)) mlatn, mlonn = convert(90, 0, 0, date=dt.date(2002, 3, 21)) for k in range(24): mltn = convert_mlt(mlonn[0], dtime=dt.datetime(2003, 3, 21, k)) ax3.scatter(mltn * 15, mlatn[0], color='r', transform=ccrs.PlateCarree()) ax3.scatter(180, 75, s=50, c='k', marker='x', transform=ccrs.PlateCarree()) ax3.text(0, 1, '(c)', transform=plt.gca().transAxes) ax4, projection4 = gcc.create_map(2, 2, 4, 'pol', -50, -90, 0, coastlines=False, useLT=True, dlat=10, lonticklabel=(1, 1, 1, 1)) mlats, mlons = convert(-90, 0, 0, date=dt.date(2002, 3, 21)) for k in range(24): mlts = convert_mlt(mlons[0], dtime=dt.datetime(2003, 3, 21, k)) ax4.scatter(mlts * 15, mlats[0], color='b', transform=ccrs.PlateCarree()) ax4.scatter(180, -75, s=50, c='k', marker='x', transform=ccrs.PlateCarree()) ax4.text(0, 1, '(d)', transform=plt.gca().transAxes) plt.savefig('/Users/guod/Documents/Pole_Density_MLT_Change/Figures/' '000_Pole_Feature.pdf') return
def plot_06ut_18ut(ns='SH', alt=150, tf=[1, 0, 0, 0, 0, 0]): # 0:rho and wind; 1: diff rho and wind; 2:ion drag; 3:vni; 4:ion convection # 5:ion density; 6:electron density; path = '/home/guod/simulation_output/momentum_analysis/run_shrink_dipole_1_c1/UA/data' fn1 = path + '/3DALL_t030322_060002.bin' fn2 = path + '/3DALL_t030322_180002.bin' g11 = [gitm.read(fn1), gitm.read(fn2)] # shrink, dipole #print(g11[0]['Altitude'][0,0,np.argmin(np.abs(g11[0]['Altitude'][0,0,:]-150*1000))]) path = '/home/guod/simulation_output/momentum_analysis/run_shrink_igrf_1_c1/UA/data' fn1 = path + '/3DALL_t030322_060002.bin' fn2 = path + '/3DALL_t030322_180003.bin' g12 = [gitm.read(fn1), gitm.read(fn2)] # shrink, igrf path = '/home/guod/simulation_output/momentum_analysis/run_no_shrink_dipole_1_1/UA/data' fn1 = path + '/3DALL_t030322_060000.bin' fn2 = path + '/3DALL_t030322_180001.bin' g21 = [gitm.read(fn1), gitm.read(fn2)] # no shrink, diple path = '/home/guod/simulation_output/momentum_analysis/run_no_shrink_igrf_1_1/UA/data' fn1 = path + '/3DALL_t030322_060001.bin' fn2 = path + '/3DALL_t030322_180002.bin' g22 = [gitm.read(fn1), gitm.read(fn2)] # no shrink, igrf if ns == 'SH': nlat, slat = -50, -90 elif ns == 'NH': nlat, slat = 90, 50 glats, glons = convert(-90, 0, 0, date=dt.date(2003, 1, 1), a2g=True) glatn, glonn = convert(90, 0, 0, date=dt.date(2003, 1, 1), a2g=True) fign = ['(a)', '(b)', '(c)', '(d)'] # Rho and wind if tf[0]: plt.figure(1, figsize=(8, 7.55)) for k in range(4): gtemp = g22 if k in [0, 1] else g21 ax, projection, hc, hq = plot_polar_contour_vector( 2, 2, k + 1, gtemp[k % 2], nlat, slat, alt, contour=True, zstr='Rho', vector=True, neuion='neu', useLT=True, coastlines=False, levels=np.linspace(0.8e-9, 1.6e-9, 21)) if k in [0, 1]: ax.scatter(glons, glats, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(glonn, glatn, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(0, 90, transform=ccrs.PlateCarree(), s=55, c='w', zorder=100) ax.scatter(0, -90, transform=ccrs.PlateCarree(), s=55, c='w', zorder=100) if k in [0, 1]: plt.title('UT: ' + gtemp[k % 2]['time'].strftime('%H'), y=1.05) if k in [0, 2]: text = 'IGRF' if k == 0 else 'Dipole' plt.text(-0.2, 0.5, text, fontsize=14, verticalalignment='center', transform=plt.gca().transAxes, rotation=90) plt.text(0, 1, fign[k], fontsize=14, transform=plt.gca().transAxes) plt.subplots_adjust(bottom=0.13, top=0.93, wspace=0.15, hspace=0.15) cax = plt.axes([0.3, 0.08, 0.4, 0.02]) plt.colorbar(hc[0], cax=cax, orientation='horizontal', ticks=np.arange(0.8e-9, 1.7e-9, 0.2e-9)) cax.set_xlabel(r'$\rho (kg/m^3)$') plt.quiverkey(hq[0], 0.5, 0.12, 500, '500m/s', coordinates='figure') plt.savefig(savepath + '2' + ns + 'RhoWind.jpeg') plt.savefig(savepath + '2' + ns + 'RhoWind.eps') # ion drag if tf[1]: plt.figure(1, figsize=(8, 7.55)) for k in range(4): gtemp = g22 if k in [0, 1] else g21 calc_rhoi(gtemp[0]) calc_rhoi(gtemp[1]) gtemp[0]['iondrag'] = \ gtemp[0]['rhoi']/gtemp[0]['Rho']*gtemp[0]['Collision(in)']*\ np.sqrt((gtemp[0]['V!Di!N (east)']-gtemp[0]['V!Dn!N (east)'])**2 +\ (gtemp[0]['V!Di!N (north)']-gtemp[0]['V!Dn!N (north)'])**2) gtemp[1]['iondrag'] = \ gtemp[1]['rhoi']/gtemp[1]['Rho']*gtemp[1]['Collision(in)']*\ np.sqrt((gtemp[1]['V!Di!N (east)']-gtemp[1]['V!Dn!N (east)'])**2 +\ (gtemp[1]['V!Di!N (north)']-gtemp[1]['V!Dn!N (north)'])**2) ax, projection, hc, hq = plot_polar_contour_vector( 2, 2, k + 1, gtemp[k % 2], nlat, slat, alt, contour=True, zstr='iondrag', vector=False, neuion='neu', useLT=True, coastlines=False, levels=np.linspace(0, 0.05, 21)) if k in [0, 1]: ax.scatter(glons, glats, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(glonn, glatn, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(0, 90, transform=ccrs.PlateCarree(), s=55, c='w', zorder=100) ax.scatter(0, -90, transform=ccrs.PlateCarree(), s=55, c='w', zorder=100) if k in [0, 1]: plt.title('UT: ' + gtemp[k % 2]['time'].strftime('%H'), y=1.05) if k in [0, 2]: text = 'IGRF' if k == 0 else 'Dipole' plt.text(-0.2, 0.5, text, fontsize=14, verticalalignment='center', transform=plt.gca().transAxes, rotation=90) plt.subplots_adjust(bottom=0.13, top=0.93, wspace=0.15, hspace=0.15) cax = plt.axes([0.3, 0.08, 0.4, 0.02]) plt.colorbar(hc[0], cax=cax, orientation='horizontal', ticks=np.arange(0, 0.051, 0.01)) cax.set_xlabel(r'Ion Drag $(m/s^2)$') plt.savefig(savepath + '3' + ns + 'IonDrag.jpeg') plt.savefig(savepath + '3' + ns + 'IonDrag.eps') # vni if tf[2]: plt.figure(1, figsize=(8, 7.55)) for k in range(4): gtemp = g22 if k in [0, 1] else g21 calc_rhoi(gtemp[0]) calc_rhoi(gtemp[1]) gtemp[0]['vni'] = \ gtemp[0]['rhoi']/gtemp[0]['Rho']*gtemp[0]['Collision(in)'] gtemp[1]['vni'] = \ gtemp[1]['rhoi']/gtemp[1]['Rho']*gtemp[1]['Collision(in)'] ax, projection, hc, hq = plot_polar_contour_vector( 2, 2, k + 1, gtemp[k % 2], nlat, slat, alt, contour=True, zstr='vni', vector=False, neuion='neu', useLT=True, coastlines=False, levels=np.linspace(0, 0.0002, 21)) if k in [0, 1]: ax.scatter(glons, glats, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(glonn, glatn, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(0, 90, transform=ccrs.PlateCarree(), s=55, c='w', zorder=100) ax.scatter(0, -90, transform=ccrs.PlateCarree(), s=55, c='w', zorder=100) if k in [0, 1]: plt.title('UT: ' + gtemp[k % 2]['time'].strftime('%H'), y=1.05) if k in [0, 2]: text = 'IGRF' if k == 0 else 'Dipole' plt.text(-0.2, 0.5, text, fontsize=14, verticalalignment='center', transform=plt.gca().transAxes, rotation=90) plt.subplots_adjust(bottom=0.13, top=0.93, wspace=0.15, hspace=0.15) cax = plt.axes([0.3, 0.08, 0.4, 0.02]) plt.colorbar(hc[0], cax=cax, orientation='horizontal', ticks=np.arange(0, 0.00021, 0.0001)) cax.set_xlabel(r'$\nu_{ni}$ $(s^{-1})$') plt.savefig(savepath + '4' + ns + 'vni.jpeg') plt.savefig(savepath + '4' + ns + 'vni.eps') # ion convection if tf[3]: plt.figure(1, figsize=(8, 7.55)) for k in range(4): gtemp = g22 if k in [0, 1] else g21 gtemp[0]['vi'] = np.sqrt(gtemp[0]['V!Di!N (east)']**2 + gtemp[0]['V!Di!N (north)']**2) gtemp[1]['vi'] = np.sqrt(gtemp[1]['V!Di!N (east)']**2 + gtemp[1]['V!Di!N (north)']**2) ax, projection, hc, hq = plot_polar_contour_vector( 2, 2, k + 1, gtemp[k % 2], nlat, slat, alt, contour=True, zstr='vi', vector=True, neuion='ion', useLT=True, coastlines=False, levels=np.linspace(0, 1000, 21)) if k in [0, 1]: ax.scatter(glons, glats, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(glonn, glatn, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(0, 90, transform=ccrs.PlateCarree(), s=55, c='w', zorder=100) ax.scatter(0, -90, transform=ccrs.PlateCarree(), s=55, c='w', zorder=100) if k in [0, 1]: plt.title('UT: ' + gtemp[k % 2]['time'].strftime('%H'), y=1.05) if k in [0, 2]: text = 'IGRF' if k == 0 else 'Dipole' plt.text(-0.2, 0.5, text, fontsize=14, verticalalignment='center', transform=plt.gca().transAxes, rotation=90) plt.subplots_adjust(bottom=0.13, top=0.93, wspace=0.15, hspace=0.15) cax = plt.axes([0.3, 0.08, 0.4, 0.02]) plt.colorbar(hc[0], cax=cax, orientation='horizontal', ticks=np.arange(0, 1001, 200)) cax.set_xlabel(r'Vi (m/s)') plt.savefig(savepath + '5' + ns + 'IonV.jpeg') plt.savefig(savepath + '5' + ns + 'IonV.eps') # ion density if tf[4]: plt.figure(1, figsize=(8, 7.55)) for k in range(4): gtemp = g22 if k in [0, 1] else g21 calc_rhoi(gtemp[0]) calc_rhoi(gtemp[1]) ax, projection, hc, hq = plot_polar_contour_vector( 2, 2, k + 1, gtemp[k % 2], nlat, slat, alt, contour=True, zstr='rhoi', vector=False, neuion='neu', useLT=True, coastlines=False, levels=np.linspace(0, 12e-15, 21)) if k in [0, 1]: ax.scatter(glons, glats, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(glonn, glatn, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(0, 90, transform=ccrs.PlateCarree(), s=55, c='w', zorder=100) ax.scatter(0, -90, transform=ccrs.PlateCarree(), s=55, c='w', zorder=100) if k in [0, 1]: plt.title('UT: ' + gtemp[k % 2]['time'].strftime('%H'), y=1.05) if k in [0, 2]: text = 'IGRF' if k == 0 else 'Dipole' plt.text(-0.2, 0.5, text, fontsize=14, verticalalignment='center', transform=plt.gca().transAxes, rotation=90) plt.subplots_adjust(bottom=0.13, top=0.93, wspace=0.15, hspace=0.15) cax = plt.axes([0.3, 0.08, 0.4, 0.02]) plt.colorbar(hc[0], cax=cax, orientation='horizontal', ticks=np.arange(0, 12.1e-15, 3e-15)) cax.set_xlabel(r'$\rho_i$ $(kg/m^3)$') plt.savefig(savepath + '6' + ns + 'Rhoi.jpeg') plt.savefig(savepath + '6' + ns + 'Rhoi.eps') # electron density if tf[5]: plt.figure(1, figsize=(8, 7.55)) for k in range(4): gtemp = g22 if k in [0, 1] else g21 calc_rhoi(gtemp[0]) calc_rhoi(gtemp[1]) ax, projection, hc, hq = plot_polar_contour_vector( 2, 2, k + 1, gtemp[k % 2], nlat, slat, alt, contour=True, zstr='e-', vector=False, neuion='neu', useLT=True, coastlines=False, levels=np.linspace(0, 0.9e12, 21)) if k in [0, 1]: ax.scatter(glons, glats, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(glonn, glatn, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(0, 90, transform=ccrs.PlateCarree(), s=55, c='w', zorder=100) ax.scatter(0, -90, transform=ccrs.PlateCarree(), s=55, c='w', zorder=100) if k in [0, 1]: plt.title('UT: ' + gtemp[k % 2]['time'].strftime('%H'), y=1.05) if k in [0, 2]: text = 'IGRF' if k == 0 else 'Dipole' plt.text(-0.2, 0.5, text, fontsize=14, verticalalignment='center', transform=plt.gca().transAxes, rotation=90) plt.subplots_adjust(bottom=0.13, top=0.93, wspace=0.15, hspace=0.15) cax = plt.axes([0.3, 0.08, 0.4, 0.02]) plt.colorbar(hc[0], cax=cax, orientation='horizontal', ticks=np.arange(0, 0.31e12, 0.1e12)) cax.set_xlabel(r'Ne ($m^{-3}$)') # plt.savefig(savepath+'7'+ns+'Ne.jpeg') # plt.savefig(savepath+'7'+ns+'Ne.eps') return
def test_convert_lat_failure(self): """Test error return for co-latitudes above 90 for an array""" with pytest.raises(AssertionError): aacgmv2.convert([91, 60, -91], 0, 300, self.dtime)
def figure1(): plt.close('all') fig = plt.figure(figsize=(5.41, 8.54)) ax = fig.add_subplot(111, projection='3d') levels = [np.linspace(6.1e-10, 17.8e-10,21), np.linspace(1.1e-10, 2.7e-10, 21), np.linspace(1.3e-11, 3.9e-11,21), np.linspace(2.6e-12, 9.503e-12,21), np.linspace(4.3e-13, 2.71e-12,21), np.linspace(7.4e-14, 8.2e-13,21)] olat = -40 olatr = np.abs(olat)/180*pi glats, glons = convert(-90,0,0,date=dt.date(2003,3,22), a2g=True) glats, glons = glats/180*pi, glons/180*pi artalt = [10, 200, 380, 540, 680, 820] realalt = [150, 200, 300, 400, 500, 600] for ik, alt in enumerate([150, 200, 300, 400, 500, 600]): lon0, lat0, rho1 = g3ca.contour_data('Rho', g1, alt=alt) lat0, lon0 = lat0/180*pi, lon0/180*pi ilat = lat0[:, 0]<=olat/180*pi lat0, lon0, rho1 = lat0[ilat,:], lon0[ilat,:], rho1[ilat,:] r = lat0+pi/2 theta = lon0 x = r*np.cos(theta) x = -x # for sorthern hemisphere y = r*np.sin(theta) v = rho1 print (np.min(v), np.max(v)) ax.contourf( x, y, v, zdir='z', offset=artalt[ik], levels=levels[ik], cmap='jet', zorder=100) ax.scatter( -(glats+pi/2)*np.cos(glons), (glats+pi/2)*np.sin(glons), artalt[ik], s=50, c='k', zorder=200) for rtick in np.arange(10,50,10)/180*pi: thetatick = np.arange(0, 2*pi, 0.01) xtick = rtick*np.cos(thetatick) ytick = rtick*np.sin(thetatick) hp = ax.plot( xtick,ytick, artalt[ik], color='0.7',linestyle=':', zorder = 300, linewidth=0.8) plt.subplots_adjust(top=1,bottom=0) ax.set_xlim(-olatr, olatr) ax.set_ylim(-olatr, olatr) ax.set_zlim(0,800) ax.axis('off') for ik, alt in enumerate(artalt): ialt = np.argmin(np.abs(g1['Altitude'][0,0,:]/1000-realalt[ik])) ax.plot([-olatr, -olatr+0.1], [-olatr, -olatr], alt, color='k') ax.text(-olatr-0.1, -olatr, alt, '%.0f km'%(g1['Altitude'][0,0,ialt]/1000), verticalalignment='center') ax.plot([-olatr, -olatr], [-olatr, -olatr], [artalt[0], artalt[-1]], color='k') ax.text(-olatr-0.3, 0, artalt[-1], '06', horizontalalignment='center', zdir='x', zorder=1000) ax.text(0, -olatr-0.3, artalt[-1], '00', horizontalalignment='center', zdir='x', zorder=1000) ax.text(olatr+0.3, 0, artalt[-1], '18', horizontalalignment='center', zdir='x', zorder=1000) ax.text(0, olatr+0.3, artalt[-1], '12', horizontalalignment='center', zdir='x', zorder=1000) plt.show() return
def figure4(): plt.close('all') plt.figure(figsize=(8.28, 9.25)) labels =[('(a)','(b)','(c)'), ('(d)','(e)','(f)'), ('(g)','(h)','(i)')] qlat, qlon = convert(-90, 0, 0, date=dt.date(2003,3,22), a2g=True) ylim = [[0.6e-9,1.6e-9], [1.5e-11, 4e-11], [1e-13, 9e-13]] for ialt, alt in enumerate([150, 300, 600]): alt_ind = np.argmin(np.abs(g1['Altitude'][0, 0, 2:-2]/1000-alt))+2 alt_str = '%6.0f' % (g1['Altitude'][0, 0, alt_ind]/1000) rho1, rho2 = g1['Rho'], g2['Rho'] rhod = 100*(rho1-rho2)/rho2 lats, lons = g1['Latitude'], g1['Longitude'] #---------------------------------------------------------------------- ax, projection = gcc.create_map( 3, 3, ialt+1, 'polar', nlat=nlat, slat=slat, dlat=10, centrallon=g3ca.calculate_centrallon(g1, 'polar', useLT=True), coastlines=False, lonticklabel=[1,1,1,1]) # density difference lon1, lat1, zdata1 = g3ca.contour_data('Rho', g1, alt=alt) lon2, lat2, zdata2 = g3ca.contour_data('Rho', g2, alt=alt) fp = (lat1[:,0]>slat) & (lat1[:,0]<nlat) lon0, lat0 = lon1[fp, :], lat1[fp,:] zdata0 = (100*(zdata1-zdata2)/zdata2)[fp, :] print(zdata0.min()) hc = ax.contourf( lon0, lat0, zdata0, np.linspace(-30,30,21), transform=ccrs.PlateCarree(), cmap='seismic', extend='both') # colorbar gcapos = ax.get_position() axcb = [ gcapos.x0, gcapos.y0+0.035, gcapos.width, gcapos.height/20] axcb = plt.axes(axcb) hcb = plt.colorbar( hc, cax=axcb, extendrect=True, ticks=np.arange(-30, 31, 15), orientation='horizontal') # wind difference lon1, lat1, ewind1, nwind1 = g3ca.vector_data(g1, 'neutral', alt=alt) lon2, lat2, ewind2, nwind2 = g3ca.vector_data(g2, 'neutral', alt=alt) lon0, lat0 = lon1, lat1 lon0, lat0, ewind0, nwind0 = g3ca.convert_vector( lon0, lat0, ewind1-ewind2, nwind1-nwind2, plot_type='polar', projection=projection) hq = ax.quiver( lon0, lat0, ewind0, nwind0, scale=1000, scale_units='inches', regrid_shape=20, headwidth=5) ax.quiverkey(hq, 0.97, 0.92, 500, '500 m/s') # magnetic pole ax.scatter(qlon, qlat, color='k', transform=ccrs.PlateCarree()) ax.scatter( 0, -90, color='w', s=30, transform=ccrs.PlateCarree(), zorder=1000) latt1 = [-90, nlat] lont1 = [15*(12-ut), 15*(12-ut)] ax.plot(lont1, latt1, transform = ccrs.PlateCarree(), c='g') latt1 = [-90, nlat] lont1 = [15*(0-ut), 15*(0-ut)] ax.plot(lont1, latt1, transform = ccrs.PlateCarree(), c='g') ax.set_title('%s km' % alt_str, y=1.07) if ialt==0: ax.text(-0.2, 0.5, r'$\delta \rho$ (%)', transform=ax.transAxes,rotation=90, fontsize=14, verticalalignment='center', horizontalalignment='center') plt.text( 0.05, 0.9, labels[0][ialt],transform=ax.transAxes,color='r') #---------------------------------------------------------------------- # density in run1 and run2 plt.subplot(3,3,ialt+7) ilat = (lats[0,:,0]/pi*180<nlat) &(lats[0,:,0]/pi*180>slat) lt = 12 ilt = np.argmin(np.abs(g1['LT'][2:-2,0,0]-lt))+2 plt.plot( 180+lats[ilt,ilat,alt_ind]/pi*180,rho1[ilt,ilat,alt_ind], 'r', label = 'Run 1') plt.plot( 180+lats[ilt,ilat,alt_ind]/pi*180,rho2[ilt,ilat,alt_ind], 'b', label = 'Run 2') plt.legend(loc='upper center') lat_1, rho_11, rho_12, rho_1d = \ 180+lats[ilt,2,alt_ind]/pi*180, rho1[ilt,2, alt_ind], \ rho2[ilt,2, alt_ind], rhod[ilt,2,alt_ind] lt = 0 ilt = np.argmin(np.abs(g1['LT'][2:-2,0,0]-lt))+2 plt.plot(-lats[ilt,ilat,alt_ind]/pi*180,rho1[ilt,ilat,alt_ind], 'r') plt.plot(-lats[ilt,ilat,alt_ind]/pi*180,rho2[ilt,ilat,alt_ind], 'b') lat_2, rho_21, rho_22, rho_2d = \ -lats[ilt,2,alt_ind]/pi*180, rho1[ilt,2, alt_ind], \ rho2[ilt,2, alt_ind], rhod[ilt,2,alt_ind] plt.plot([lat_1,lat_2], [rho_11,rho_21], 'r') plt.plot([lat_1,lat_2], [rho_12,rho_22], 'b') plt.grid('on') plt.xlim([-nlat,180+nlat]) plt.ylim(ylim[ialt]) plt.xticks(np.arange(-nlat,181+nlat,30), np.concatenate( [np.arange(nlat,-90,-30), np.arange(-90,nlat+1,30)])) if ialt==0: plt.ylabel(r'$\rho$ (kg/m$^3$)', fontsize=14) plt.xlabel('Latitude') plt.text( 0.05, 0.9, labels[2][ialt],transform=plt.gca().transAxes,color='r') #---------------------------------------------------------------------- # density difference plt.subplot(3,3,ialt+4) lt = 12 ilt = np.argmin(np.abs(g1['LT'][2:-2,0,0]-lt))+2 plt.plot( 180+lats[ilt,ilat,alt_ind]/pi*180,rhod[ilt,ilat,alt_ind], 'k') lt = 0 ilt = np.argmin(np.abs(g1['LT'][2:-2,0,0]-lt))+2 plt.plot( -lats[ilt,ilat,alt_ind]/pi*180,rhod[ilt,ilat,alt_ind], 'k') plt.plot([lat_1,lat_2], [rho_1d,rho_2d], 'k') plt.grid('on') plt.xlim([-nlat,180+nlat]) plt.xticks(np.arange(-nlat,181+nlat,30), np.concatenate( [np.arange(nlat,-90,-30), np.arange(-90,nlat+1,30)])) plt.ylim(-35, 5) plt.yticks(np.arange(-30, 0.1, 10)) if ialt==0: plt.ylabel(r'$\delta\rho$ (%)', fontsize=14) plt.xlabel('Latitude') plt.text( 0.05, 0.9, labels[1][ialt],transform=plt.gca().transAxes,color='r') plt.subplots_adjust(wspace=0.25, hspace=0.25, top=0.95, bottom=0.05) plt.savefig(savepath+'Figure4.eps') plt.savefig(savepath+'Figure4.jpeg') return
def test_warning_below_ground(): with pytest.warns(UserWarning): aacgmv2.convert(60, 0, -1, dtObj) with pytest.warns(UserWarning): aacgmv2.convert(60, 0, [300, -1], dtObj)
def test_convert_maxalt_failure(self): """For an array, test failure for an altitude too high for coefficients""" with pytest.raises(ValueError): aacgmv2.convert([60], [0], [2001], self.dtime)
def readDay(hemiSN, dt, deltaT=2, fileType='grdex', src=None, fileName=None, custType='grdex', noCache=False): """Read one day and hemisphere of SuperDARN data (All of these other options are passed through just_sam to DavitPy) Parameters ---------- hemiSN: N or S dt : TYPE Description deltaT : int, optional Description fileType : str, optional Description src : None, optional Description fileName : None, optional Description custType : str, optional Description noCache : bool, optional Description Returns ------- TYPE Description """ #import davitpy.models.aacgm as aacgm #def _sdGridLoad(sTime,eTime,deltaT,hemi,fileType,src,fileName,custType,noCache,estd=False,TWidth=None): #SAM uses different hemisphere naming convention if hemiSN is 'N': hemi = 'north' elif hemiSN is 'S': hemi = 'south' #Load in data in 2 minute chunks sdList = _sdGridLoad(dt, dt + datetime.timedelta(days=1), deltaT, hemi, fileType, src, fileName, custType, noCache, estd=False, TWidth=None) #Split out data into numpy arrays #Each sdI is a griddata object from pydarn.sdio.sdDataTypes startdts, enddts = [], [] mlats, mlons, mltlons, vels, verrs, azms, rids = [], [], [], [], [], [], [] eloss, eerrs = [], [] #Electric fields will be compute inplace bigrfs = [] for sdI in sdList: if sdI.vector.mlat is None or sdI.vector.mlon is None: print sdI.vector continue startdts.append(sdI.sTime) enddts.append(sdI.eTime) mlat = np.asarray(sdI.vector.mlat) mlats.append(mlat) #Do in-band MLT conversion mlon = np.asarray(sdI.vector.mlon) y, M, d = sdI.sTime.year, sdI.sTime.month, sdI.sTime.day h, m, s = sdI.sTime.hour, sdI.sTime.minute, sdI.sTime.second # mltDef = aacgm.mltFromYmdhms(y,M,d,h,m,s,0.0) * 15. # mltDef is the rotation that needs to be applied, # and lon is the AACGM longitude. # use modulo so new longitude is between 0 & 360 # mlt_lon = np.mod((mlon + mltDef), 360.) mlt_lon = aacgmv2.convert_mlt(mlon, sdI.sTime, False) ## sishen added mlons.append(mlon) #Actual mlon mltlons.append(mlt_lon) #MLT in degrees #Convert to electric field vel = np.asarray(sdI.vector.velmedian) verr = np.asarray(sdI.vector.velsd) vels.append(vel) verrs.append(verr) # Where do superDARN returns come from? approx_alt = 300. #Could use either Apex-Python or AACGMv2 package #for magnetic to geocentric conversion gdlat, gdlon = aacgmv2.convert(mlat, mlon, approx_alt, date=sdI.sTime, a2g=True) #gdlat,gdlon = ac.apex2geo(mlat,mlon,approx_alt) Be, Bn, Bu = igrfpy.getmainfield(sdI.sTime, gdlat, gdlon, np.ones_like(gdlat) * approx_alt, geocentric=False, silent=True) Bu = np.abs(np.array(Bu)) # It returns lists # Convert SuperDARN Vlos to E-field # (Should be using IGRF...just using constant instead) # Will change after compare with SAM #Bconst = 0.5e-4 bigrfs.append(Bu * 1.0e-9) eloss.append(vel * Bu * 1.0e-9) eerrs.append(verr * Bu * 1.0e-9) azms.append(np.asarray(sdI.vector.kvect)) #degrees rids.append(np.asarray(sdI.vector.stid)) #station id num return (startdts, enddts, mlats, mlons, mltlons, vels, verrs, eloss, eerrs, azms, rids, bigrfs)
def test_convert_datetime_date(self): """Test conversion with date and datetime input""" self.lat, self.lon = aacgmv2.convert([60], [0], [300], self.ddate) np.testing.assert_allclose(self.lat, [58.2258], rtol=1e-4) np.testing.assert_allclose(self.lon, [81.1685], rtol=1e-4)
def test_forbidden(): mlat, mlon = aacgmv2.convert(7, 0, 0) assert np.isnan(mlat) assert np.isnan(mlon)
def test_convert_result_values_G2A_coeff(): lat_p, lon_p = aacgmv2.convert(60, 0, 300, dtObj) aacgmv2._aacgmv2.setDateTime(*date) lat_c, lon_c, _ = aacgmv2._aacgmv2.aacgmConvert(60, 0, 300, G2A) assert lat_p == lat_c assert lon_p == lon_c
def plot_06ut_18ut(ns='SH',alt=150,tf=[1,0,0,0,0,0]): # 0:rho and wind; 1: diff rho and wind; 2:ion drag; 3:vni; 4:ion convection # 5:ion density; 6:electron density; path = '/home/guod/simulation_output/momentum_analysis/run_shrink_dipole_1_c1/UA/data' fn1 = path+'/3DALL_t030322_060002.bin' fn2 = path+'/3DALL_t030322_180002.bin' g11 = [gitm.read(fn1), gitm.read(fn2)] # shrink, dipole #print(g11[0]['Altitude'][0,0,np.argmin(np.abs(g11[0]['Altitude'][0,0,:]-150*1000))]) path = '/home/guod/simulation_output/momentum_analysis/run_shrink_igrf_1_c1/UA/data' fn1 = path+'/3DALL_t030322_060002.bin' fn2 = path+'/3DALL_t030322_180003.bin' g12 = [gitm.read(fn1), gitm.read(fn2)] # shrink, igrf path = '/home/guod/simulation_output/momentum_analysis/run_no_shrink_dipole_1_1/UA/data' fn1 = path+'/3DALL_t030322_060000.bin' fn2 = path+'/3DALL_t030322_180001.bin' g21 = [gitm.read(fn1), gitm.read(fn2)] # no shrink, diple path = '/home/guod/simulation_output/momentum_analysis/run_no_shrink_igrf_1_1/UA/data' fn1 = path+'/3DALL_t030322_060001.bin' fn2 = path+'/3DALL_t030322_180002.bin' g22 = [gitm.read(fn1), gitm.read(fn2)] # no shrink, igrf if ns == 'SH': nlat, slat = -50, -90 elif ns == 'NH': nlat, slat = 90, 50 glats, glons = convert(-90, 0, 0, date=dt.date(2003,1,1), a2g=True) glatn, glonn = convert(90, 0, 0, date=dt.date(2003,1,1), a2g=True) fign=['(a)','(b)','(c)','(d)'] # Rho and wind if tf[0]: plt.figure(1, figsize=(8, 7.55)) for k in range(4): gtemp = g22 if k in [0, 1] else g21 ax, projection, hc, hq = plot_polar_contour_vector( 2, 2, k+1, gtemp[k%2], nlat, slat, alt, contour=True, zstr='Rho', vector=True, neuion='neu', useLT=True, coastlines=False, levels=np.linspace(0.8e-9, 1.6e-9, 21)) if k in [0, 1]: ax.scatter(glons, glats, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(glonn, glatn, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(0, 90, transform=ccrs.PlateCarree(), s=55, c='w',zorder=100) ax.scatter(0, -90, transform=ccrs.PlateCarree(), s=55, c='w',zorder=100) if k in [0, 1]: plt.title('UT: '+gtemp[k%2]['time'].strftime('%H'), y=1.05) if k in [0, 2]: text = 'IGRF' if k==0 else 'Dipole' plt.text( -0.2, 0.5, text, fontsize=14, verticalalignment='center', transform=plt.gca().transAxes, rotation=90) plt.text( 0, 1, fign[k], fontsize=14, transform=plt.gca().transAxes) plt.subplots_adjust(bottom=0.13,top=0.93, wspace=0.15, hspace=0.15) cax = plt.axes([0.3, 0.08, 0.4, 0.02]) plt.colorbar( hc[0], cax=cax, orientation='horizontal', ticks=np.arange(0.8e-9, 1.7e-9, 0.2e-9)) cax.set_xlabel(r'$\rho (kg/m^3)$') plt.quiverkey(hq[0], 0.5,0.12, 500, '500m/s',coordinates='figure') plt.savefig(savepath+'2'+ns+'RhoWind.jpeg') plt.savefig(savepath+'2'+ns+'RhoWind.eps') # ion drag if tf[1]: plt.figure(1, figsize=(8, 7.55)) for k in range(4): gtemp = g22 if k in [0, 1] else g21 calc_rhoi(gtemp[0]) calc_rhoi(gtemp[1]) gtemp[0]['iondrag'] = \ gtemp[0]['rhoi']/gtemp[0]['Rho']*gtemp[0]['Collision(in)']*\ np.sqrt((gtemp[0]['V!Di!N (east)']-gtemp[0]['V!Dn!N (east)'])**2 +\ (gtemp[0]['V!Di!N (north)']-gtemp[0]['V!Dn!N (north)'])**2) gtemp[1]['iondrag'] = \ gtemp[1]['rhoi']/gtemp[1]['Rho']*gtemp[1]['Collision(in)']*\ np.sqrt((gtemp[1]['V!Di!N (east)']-gtemp[1]['V!Dn!N (east)'])**2 +\ (gtemp[1]['V!Di!N (north)']-gtemp[1]['V!Dn!N (north)'])**2) ax, projection, hc, hq = plot_polar_contour_vector( 2, 2, k+1, gtemp[k%2], nlat, slat, alt, contour=True, zstr='iondrag', vector=False, neuion='neu', useLT=True, coastlines=False, levels=np.linspace(0, 0.05, 21)) if k in [0, 1]: ax.scatter(glons, glats, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(glonn, glatn, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(0, 90, transform=ccrs.PlateCarree(), s=55, c='w',zorder=100) ax.scatter(0, -90, transform=ccrs.PlateCarree(), s=55, c='w',zorder=100) if k in [0, 1]: plt.title('UT: '+gtemp[k%2]['time'].strftime('%H'), y=1.05) if k in [0, 2]: text = 'IGRF' if k==0 else 'Dipole' plt.text( -0.2, 0.5, text, fontsize=14, verticalalignment='center', transform=plt.gca().transAxes, rotation=90) plt.subplots_adjust(bottom=0.13,top=0.93, wspace=0.15, hspace=0.15) cax = plt.axes([0.3, 0.08, 0.4, 0.02]) plt.colorbar( hc[0], cax=cax, orientation='horizontal', ticks=np.arange(0, 0.051, 0.01)) cax.set_xlabel(r'Ion Drag $(m/s^2)$') plt.savefig(savepath+'3'+ns+'IonDrag.jpeg') plt.savefig(savepath+'3'+ns+'IonDrag.eps') # vni if tf[2]: plt.figure(1, figsize=(8, 7.55)) for k in range(4): gtemp = g22 if k in [0, 1] else g21 calc_rhoi(gtemp[0]) calc_rhoi(gtemp[1]) gtemp[0]['vni'] = \ gtemp[0]['rhoi']/gtemp[0]['Rho']*gtemp[0]['Collision(in)'] gtemp[1]['vni'] = \ gtemp[1]['rhoi']/gtemp[1]['Rho']*gtemp[1]['Collision(in)'] ax, projection, hc, hq = plot_polar_contour_vector( 2, 2, k+1, gtemp[k%2], nlat, slat, alt, contour=True, zstr='vni', vector=False, neuion='neu', useLT=True, coastlines=False, levels=np.linspace(0, 0.0002, 21)) if k in [0, 1]: ax.scatter(glons, glats, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(glonn, glatn, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(0, 90, transform=ccrs.PlateCarree(), s=55, c='w',zorder=100) ax.scatter(0, -90, transform=ccrs.PlateCarree(), s=55, c='w',zorder=100) if k in [0, 1]: plt.title('UT: '+gtemp[k%2]['time'].strftime('%H'), y=1.05) if k in [0, 2]: text = 'IGRF' if k==0 else 'Dipole' plt.text( -0.2, 0.5, text, fontsize=14, verticalalignment='center', transform=plt.gca().transAxes, rotation=90) plt.subplots_adjust(bottom=0.13,top=0.93, wspace=0.15, hspace=0.15) cax = plt.axes([0.3, 0.08, 0.4, 0.02]) plt.colorbar( hc[0], cax=cax, orientation='horizontal', ticks=np.arange(0, 0.00021, 0.0001)) cax.set_xlabel(r'$\nu_{ni}$ $(s^{-1})$') plt.savefig(savepath+'4'+ns+'vni.jpeg') plt.savefig(savepath+'4'+ns+'vni.eps') # ion convection if tf[3]: plt.figure(1, figsize=(8, 7.55)) for k in range(4): gtemp = g22 if k in [0, 1] else g21 gtemp[0]['vi'] = np.sqrt( gtemp[0]['V!Di!N (east)']**2 + gtemp[0]['V!Di!N (north)']**2) gtemp[1]['vi'] = np.sqrt( gtemp[1]['V!Di!N (east)']**2 + gtemp[1]['V!Di!N (north)']**2) ax, projection, hc, hq = plot_polar_contour_vector( 2, 2, k+1, gtemp[k%2], nlat, slat, alt, contour=True, zstr='vi', vector=True, neuion='ion', useLT=True, coastlines=False, levels=np.linspace(0, 1000, 21)) if k in [0, 1]: ax.scatter(glons, glats, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(glonn, glatn, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(0, 90, transform=ccrs.PlateCarree(), s=55, c='w',zorder=100) ax.scatter(0, -90, transform=ccrs.PlateCarree(), s=55, c='w',zorder=100) if k in [0, 1]: plt.title('UT: '+gtemp[k%2]['time'].strftime('%H'), y=1.05) if k in [0, 2]: text = 'IGRF' if k==0 else 'Dipole' plt.text( -0.2, 0.5, text, fontsize=14, verticalalignment='center', transform=plt.gca().transAxes, rotation=90) plt.subplots_adjust(bottom=0.13,top=0.93, wspace=0.15, hspace=0.15) cax = plt.axes([0.3, 0.08, 0.4, 0.02]) plt.colorbar( hc[0], cax=cax, orientation='horizontal', ticks=np.arange(0, 1001, 200)) cax.set_xlabel(r'Vi (m/s)') plt.savefig(savepath+'5'+ns+'IonV.jpeg') plt.savefig(savepath+'5'+ns+'IonV.eps') # ion density if tf[4]: plt.figure(1, figsize=(8, 7.55)) for k in range(4): gtemp = g22 if k in [0, 1] else g21 calc_rhoi(gtemp[0]) calc_rhoi(gtemp[1]) ax, projection, hc, hq = plot_polar_contour_vector( 2, 2, k+1, gtemp[k%2], nlat, slat, alt, contour=True, zstr='rhoi', vector=False, neuion='neu', useLT=True, coastlines=False, levels=np.linspace(0, 12e-15, 21)) if k in [0, 1]: ax.scatter(glons, glats, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(glonn, glatn, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(0, 90, transform=ccrs.PlateCarree(), s=55, c='w',zorder=100) ax.scatter(0, -90, transform=ccrs.PlateCarree(), s=55, c='w',zorder=100) if k in [0, 1]: plt.title('UT: '+gtemp[k%2]['time'].strftime('%H'), y=1.05) if k in [0, 2]: text = 'IGRF' if k==0 else 'Dipole' plt.text( -0.2, 0.5, text, fontsize=14, verticalalignment='center', transform=plt.gca().transAxes, rotation=90) plt.subplots_adjust(bottom=0.13,top=0.93, wspace=0.15, hspace=0.15) cax = plt.axes([0.3, 0.08, 0.4, 0.02]) plt.colorbar( hc[0], cax=cax, orientation='horizontal', ticks=np.arange(0, 12.1e-15, 3e-15)) cax.set_xlabel(r'$\rho_i$ $(kg/m^3)$') plt.savefig(savepath+'6'+ns+'Rhoi.jpeg') plt.savefig(savepath+'6'+ns+'Rhoi.eps') # electron density if tf[5]: plt.figure(1, figsize=(8, 7.55)) for k in range(4): gtemp = g22 if k in [0, 1] else g21 calc_rhoi(gtemp[0]) calc_rhoi(gtemp[1]) ax, projection, hc, hq = plot_polar_contour_vector( 2, 2, k+1, gtemp[k%2], nlat, slat, alt, contour=True, zstr='e-', vector=False, neuion='neu', useLT=True, coastlines=False, levels=np.linspace(0, 0.9e12, 21)) if k in [0, 1]: ax.scatter(glons, glats, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(glonn, glatn, transform=ccrs.PlateCarree(), s=55, c='k') ax.scatter(0, 90, transform=ccrs.PlateCarree(), s=55, c='w',zorder=100) ax.scatter(0, -90, transform=ccrs.PlateCarree(), s=55, c='w',zorder=100) if k in [0, 1]: plt.title('UT: '+gtemp[k%2]['time'].strftime('%H'), y=1.05) if k in [0, 2]: text = 'IGRF' if k==0 else 'Dipole' plt.text( -0.2, 0.5, text, fontsize=14, verticalalignment='center', transform=plt.gca().transAxes, rotation=90) plt.subplots_adjust(bottom=0.13,top=0.93, wspace=0.15, hspace=0.15) cax = plt.axes([0.3, 0.08, 0.4, 0.02]) plt.colorbar( hc[0], cax=cax, orientation='horizontal', ticks=np.arange(0, 0.31e12, 0.1e12)) cax.set_xlabel(r'Ne ($m^{-3}$)') # plt.savefig(savepath+'7'+ns+'Ne.jpeg') # plt.savefig(savepath+'7'+ns+'Ne.eps') return
def figure5_7_refer(alt=300): times = pd.to_datetime([ '2003-03-22 00:00:00', '2003-03-22 00:30:00', '2003-03-22 01:00:00', '2003-03-22 02:00:00', '2003-03-22 03:00:00', '2003-03-22 06:00:00']) plt.close('all') plt.figure(figsize=(3, 9.25)) ylabel = times.strftime('%H:%M') qlat, qlon = convert(-90, 0, 0, date=dt.date(2003,3,22), a2g=True) for itime, time in enumerate(times): strtime = time.strftime('%y%m%d_%H%M') fn1 = glob.glob( '/home/guod/simulation_output/momentum_analysis/'\ 'run_no_shrink_iondrift_4_1/data/3DALL_t%s*.bin' % strtime) fn2 = glob.glob( '/home/guod/simulation_output/momentum_analysis/'\ 'run_shrink_iondrift_4_c1/data/3DALL_t%s*.bin' % strtime) g1 = gitm.read(fn1[0]) g2 = gitm.read(fn2[0]) lon1, lat1, alt1, T1 = \ g1['Longitude'], g1['Latitude'], g1['Altitude'], g1['Temperature'] lon2, lat2, alt2, T2 = \ g2['Longitude'], g2['Latitude'], g2['Altitude'], g2['Temperature'] alt_ind = np.argmin(np.abs(alt1[0, 0, :]/1000-alt)) alt_str = '%6.0f' % (alt1[0, 0, alt_ind]/1000) lonticklabel=[0, 1, 0, 1] if itime == 0: lonticklabel[0] = 1 if itime == 5: lonticklabel[2] = 1 ax, projection = gcc.create_map( 6, 1, itime+1, 'polar', nlat=nlat, slat=slat, dlat=10, centrallon=g3ca.calculate_centrallon(g1, 'polar', useLT=True), coastlines=False, lonticklabel=lonticklabel) g1['temp'] = T1-T2 lon0, lat0, zdata0 = g3ca.contour_data('temp', g1, alt=alt) fp = (lat0[:,0]>slat) & (lat0[:,0]<nlat) lon0, lat0, zdata0 = lon0[fp, :], lat0[fp,:], zdata0[fp,:] hc = ax.contourf( lon0, lat0, zdata0, levels=np.linspace(-60, 60, 21), transform=ccrs.PlateCarree(), cmap='seismic', extend='both') # wind difference lon1, lat1, ewind1, nwind1 = g3ca.vector_data( g1, 'neutral', alt=alt) lon2, lat2, ewind2, nwind2 = g3ca.vector_data( g2, 'neutral', alt=alt) lon0, lat0 = lon1, lat1 lon0, lat0, ewind0, nwind0 = g3ca.convert_vector( lon0, lat0, ewind1-ewind2, nwind1-nwind2, plot_type='polar', projection=projection) hq = ax.quiver( lon0, lat0, ewind0, nwind0, scale=1500, scale_units='inches', regrid_shape=20, headwidth=5) ax.scatter( qlon, qlat, s=10, color='k', transform=ccrs.PlateCarree()) ax.scatter( 0, -90, color='w', s=10, transform=ccrs.PlateCarree(), zorder=1000) plt.text( -0.3, 0.5, ylabel[itime], rotation=90, transform=ax.transAxes, verticalalignment='center') if itime==0: plt.title(r'$T_d$ (K)', y=1.15) if itime==5: axp = ax.get_position() cax = [axp.x0, axp.y0-0.03, axp.x1-axp.x0, 1/20*(axp.y1-axp.y0)] cax = plt.axes(cax) ticks = np.arange(-60, 61, 20) hcb = plt.colorbar( hc, cax=cax, extendrect=True, orientation='horizontal', ticks=ticks) plt.subplots_adjust(wspace=0, hspace=0) plt.show() return
def test_convert_datetime_date(): lat_1, lon_1 = aacgmv2.convert(60, 0, 300, dt.date(2013, 12, 1)) lat_2, lon_2 = aacgmv2.convert(60, 0, 300, dt.datetime(2013, 12, 1, 0, 0, 0)) assert lat_1 == lat_2 assert lon_1 == lon_2
def test_convert_time_failure(self): """Test conversion with a bad time""" with pytest.raises(AssertionError): self.lat, self.lon = aacgmv2.convert([60], [0], [300], None)
lonticklabel=(1, 1, 1, 1)) ax2.scatter(0, -90, color='b', transform=ccrs.PlateCarree()) #geomagnetic coordinates ax3, projection3 = gcc.create_map(2, 2, 3, 'pol', 90, 50, 0, coastlines=False, useLT=True, dlat=10, lonticklabel=(1, 1, 1, 1)) mlatn, mlonn = convert(90, 0, 0, date=dt.date(2002, 3, 21)) for k in range(24): mltn = convert_mlt(mlonn[0], dtime=dt.datetime(2003, 3, 21, k)) ax3.scatter(mltn * 15, mlatn[0], color='r', transform=ccrs.PlateCarree()) ax3.scatter(180, 75, s=50, c='k', marker='x', transform=ccrs.PlateCarree()) ax4, projection4 = gcc.create_map(2, 2, 4, 'pol', -50, -90, 0, coastlines=False, useLT=True, dlat=10,
g2 = gitm.read(path2) fig = plt.figure(figsize=(5.41, 8.54)) ax = fig.add_subplot(111, projection='3d') levels = [ np.linspace(6.1e-10, 17.8e-10, 21), np.linspace(1.1e-10, 2.7e-10, 21), np.linspace(1.3e-11, 3.9e-11, 21), np.linspace(2.6e-12, 9.503e-12, 21), np.linspace(4.3e-13, 2.71e-12, 21), np.linspace(7.4e-14, 8.2e-13, 21) ] olat = -40 olatr = np.abs(olat) / 180 * np.pi glats, glons = convert(-90, 0, 0, date=dt.date(2003, 3, 22), a2g=True) glats, glons = glats / 180 * pi, glons / 180 * pi artalt = [10, 200, 380, 540, 680, 820] realalt = [150, 200, 300, 400, 500, 600] for ik, alt in enumerate([150, 200, 300, 400, 500, 600]): lon0, lat0, rho1 = g3ca.contour_data('Rho', g1, alt=alt) lon0, lat0, rho2 = g3ca.contour_data('Rho', g2, alt=alt) lat0, lon0 = lat0 / 180 * pi, lon0 / 180 * pi ilat = lat0[:, 0] <= olat / 180 * np.pi lat0, lon0, rho1, rho2 = \ lat0[ilat,:], lon0[ilat,:], rho1[ilat,:], rho2[ilat,:] r = lat0 + pi / 2 theta = lon0 x = r * np.cos(theta) x = -x # for sorthern hemisphere
dlat=10, lonticklabel=(1, 1, 1, 1)) ax1.plot([45,45],[50,90], 'k--',transform=ccrs.PlateCarree()) ax1.plot([225,225],[50,90], 'k--',transform=ccrs.PlateCarree()) ax1.plot([105,105],[50,90], 'k--',transform=ccrs.PlateCarree()) ax1.plot([285,285],[50,90], 'k--',transform=ccrs.PlateCarree()) ax1.scatter(0, 90, color='r', transform=ccrs.PlateCarree(), zorder=10) ax2, projection2 = gcc.create_map( 2, 2, 2, 'pol', -50, -90, 0, coastlines=False,useLT=True, dlat=10, lonticklabel=(1, 1, 1, 1)) ax2.scatter(0, -90, color='b', transform=ccrs.PlateCarree()) #geomagnetic coordinates ax3, projection3 = gcc.create_map( 2, 2, 3, 'pol', 90, 50, 0, coastlines=False,useLT=True, dlat=10, lonticklabel=(1, 1, 1, 1)) mlatn,mlonn = convert(90,0,0,date=dt.date(2002,3,21)) for k in range(24): mltn = convert_mlt(mlonn[0],dtime=dt.datetime(2003,3,21,k)) ax3.scatter(mltn*15,mlatn[0],color='r',transform=ccrs.PlateCarree()) ax3.scatter(180,75,s=50,c='k',marker='x',transform=ccrs.PlateCarree()) ax4, projection4 = gcc.create_map( 2, 2, 4, 'pol', -50, -90, 0, coastlines=False,useLT=True, dlat=10, lonticklabel=(1, 1, 1, 1)) mlats,mlons = convert(-90,0,0,date=dt.date(2002,3,21)) for k in range(24): mlts = convert_mlt(mlons[0],dtime=dt.datetime(2003,3,21,k)) ax4.scatter(mlts*15,mlats[0],color='b',transform=ccrs.PlateCarree()) ax4.scatter(180,-75,s=50,c='k',marker='x',transform=ccrs.PlateCarree()) plt.savefig('/Users/guod/Documents/Thesis/006SciFig/work3_001.eps') #plt.show()
def plot_rho_wind_ut(ns='SH', alt=150): path = '/home/guod/simulation_output/momentum_analysis/run_no_shrink_igrf_1_1/data' fn01 = path+'/3DALL_t030323_000000.bin' fn02 = path+'/3DALL_t030323_030000.bin' fn03 = path+'/3DALL_t030323_060001.bin' fn04 = path+'/3DALL_t030323_090002.bin' fn05 = path+'/3DALL_t030323_120000.bin' fn06 = path+'/3DALL_t030323_150001.bin' fn07 = path+'/3DALL_t030323_180000.bin' fn08 = path+'/3DALL_t030323_210002.bin' fn09 = path+'/3DALL_t030324_000000.bin' fn2 = [fn01, fn02, fn03, fn04, fn05, fn06, fn07, fn08, fn09] if ns=='SH': nlat, slat = -50, -90 elif ns=='NH': nlat, slat = 90, 50 glats, glons = convert(-90, 0, 0, date=dt.date(2003,1,1), a2g=True) glatn, glonn = convert(90, 0, 0, date=dt.date(2003,1,1), a2g=True) fig1 = plt.figure(1, figsize=(5.28,8.49)) titf = ['(a)','(b)','(c)','(d)','(e)','(f)','(g)','(h)'] for k in range(8): g2 = gitm.read(fn2[k]) title = 'UT: '+g2['time'].strftime('%H') lon2, lat2, rho2 = g3ca.contour_data('Rho', g2, alt=alt) ilat2 = (lat2[:,0]>=slat) & (lat2[:,0]<=nlat) min_div_mean = \ np.min(rho2[ilat2, :]) / \ (np.mean(rho2[ilat2, :]*np.cos(lat2[ilat2, :]/180*np.pi)) /\ np.mean(np.cos(lat2[ilat2,:]/180*np.pi))) print(ns,': ',100*(min_div_mean-1)) lon2, lat2, ewind2, nwind2 = g3ca.vector_data(g2,'neu',alt=alt) if k ==0: lonticklabel = [1, 0, 0, 1] elif k==1: lonticklabel = [1, 1, 0, 0] elif k in [2, 4]: lonticklabel = [0, 0, 0, 1] elif k in [3, 5]: lonticklabel = [0, 1, 0, 0] elif k==6: lonticklabel = [0, 0, 1, 1] elif k==7: lonticklabel = [0, 1, 1, 0] olat=False if k<7 else True # No shrink plt.figure(1) centrallon = g3ca.calculate_centrallon(g2, 'pol', useLT=True) ax, projection = gcc.create_map( 4,2,k+1, 'pol', nlat, slat, centrallon, coastlines=False, dlat=10, useLT=True, lonticklabel=lonticklabel, olat=olat) hc1 = ax.contourf(lon2, lat2, rho2, np.linspace(0.8e-9, 1.6e-9), transform=ccrs.PlateCarree(),cmap='jet', extend='both') lon9, lat9, ewind9, nwind9 = g3ca.convert_vector( lon2, lat2, ewind2, nwind2, 'pol', projection) hq1 = ax.quiver( lon9,lat9,ewind9,nwind9,scale=1500,scale_units='inches', regrid_shape=20) ax.scatter(glons, glats, transform=ccrs.PlateCarree(), s=35, c='k') ax.scatter(glonn, glatn, transform=ccrs.PlateCarree(), s=35, c='k') ax.scatter(0, 90, transform=ccrs.PlateCarree(), s=35, c='w', zorder=100) ax.scatter(0, -90, transform=ccrs.PlateCarree(), s=35, c='w', zorder=100) plt.title(titf[k]+' '+title,x=0,y=0.93) plt.figure(1) plt.subplots_adjust( hspace=0.01, wspace=0.01, left=0.05, right=0.95, top=0.95, bottom=0.12) cax = plt.axes([0.25,0.07,0.5,0.02]) hcb = plt.colorbar( hc1,cax=cax,orientation='horizontal',ticks=np.arange(0.8,1.7,0.2)*1e-9) hcb.set_label(r'$\rho$ (kg/$m^3$)') plt.quiverkey(hq1, 0.5,0.12, 500, '500m/s',coordinates='figure') plt.savefig(savepath+'1'+ns+'AllUT.eps') plt.savefig(savepath+'1'+ns+'AllUT.jpeg') return
def plot_rho_wind_ut(ns='SH', alt=150): path = '/home/guod/simulation_output/momentum_analysis/run_no_shrink_igrf_1_1/data' fn01 = path + '/3DALL_t030323_000000.bin' fn02 = path + '/3DALL_t030323_030000.bin' fn03 = path + '/3DALL_t030323_060001.bin' fn04 = path + '/3DALL_t030323_090002.bin' fn05 = path + '/3DALL_t030323_120000.bin' fn06 = path + '/3DALL_t030323_150001.bin' fn07 = path + '/3DALL_t030323_180000.bin' fn08 = path + '/3DALL_t030323_210002.bin' fn09 = path + '/3DALL_t030324_000000.bin' fn2 = [fn01, fn02, fn03, fn04, fn05, fn06, fn07, fn08, fn09] if ns == 'SH': nlat, slat = -50, -90 elif ns == 'NH': nlat, slat = 90, 50 glats, glons = convert(-90, 0, 0, date=dt.date(2003, 1, 1), a2g=True) glatn, glonn = convert(90, 0, 0, date=dt.date(2003, 1, 1), a2g=True) fig1 = plt.figure(1, figsize=(5.28, 8.49)) titf = ['(a)', '(b)', '(c)', '(d)', '(e)', '(f)', '(g)', '(h)'] for k in range(8): g2 = gitm.read(fn2[k]) title = 'UT: ' + g2['time'].strftime('%H') lon2, lat2, rho2 = g3ca.contour_data('Rho', g2, alt=alt) ilat2 = (lat2[:, 0] >= slat) & (lat2[:, 0] <= nlat) min_div_mean = \ np.min(rho2[ilat2, :]) / \ (np.mean(rho2[ilat2, :]*np.cos(lat2[ilat2, :]/180*np.pi)) /\ np.mean(np.cos(lat2[ilat2,:]/180*np.pi))) print(ns, ': ', 100 * (min_div_mean - 1)) lon2, lat2, ewind2, nwind2 = g3ca.vector_data(g2, 'neu', alt=alt) if k == 0: lonticklabel = [1, 0, 0, 1] elif k == 1: lonticklabel = [1, 1, 0, 0] elif k in [2, 4]: lonticklabel = [0, 0, 0, 1] elif k in [3, 5]: lonticklabel = [0, 1, 0, 0] elif k == 6: lonticklabel = [0, 0, 1, 1] elif k == 7: lonticklabel = [0, 1, 1, 0] olat = False if k < 7 else True # No shrink plt.figure(1) centrallon = g3ca.calculate_centrallon(g2, 'pol', useLT=True) ax, projection = gcc.create_map(4, 2, k + 1, 'pol', nlat, slat, centrallon, coastlines=False, dlat=10, useLT=True, lonticklabel=lonticklabel, olat=olat) hc1 = ax.contourf(lon2, lat2, rho2, np.linspace(0.8e-9, 1.6e-9), transform=ccrs.PlateCarree(), cmap='jet', extend='both') lon9, lat9, ewind9, nwind9 = g3ca.convert_vector( lon2, lat2, ewind2, nwind2, 'pol', projection) hq1 = ax.quiver(lon9, lat9, ewind9, nwind9, scale=1500, scale_units='inches', regrid_shape=20) ax.scatter(glons, glats, transform=ccrs.PlateCarree(), s=35, c='k') ax.scatter(glonn, glatn, transform=ccrs.PlateCarree(), s=35, c='k') ax.scatter(0, 90, transform=ccrs.PlateCarree(), s=35, c='w', zorder=100) ax.scatter(0, -90, transform=ccrs.PlateCarree(), s=35, c='w', zorder=100) plt.title(titf[k] + ' ' + title, x=0, y=0.93) plt.figure(1) plt.subplots_adjust(hspace=0.01, wspace=0.01, left=0.05, right=0.95, top=0.95, bottom=0.12) cax = plt.axes([0.25, 0.07, 0.5, 0.02]) hcb = plt.colorbar(hc1, cax=cax, orientation='horizontal', ticks=np.arange(0.8, 1.7, 0.2) * 1e-9) hcb.set_label(r'$\rho$ (kg/$m^3$)') plt.quiverkey(hq1, 0.5, 0.12, 500, '500m/s', coordinates='figure') plt.savefig(savepath + '1' + ns + 'AllUT.eps') plt.savefig(savepath + '1' + ns + 'AllUT.jpeg') return
path1 = '/home/guod/simulation_output/momentum_analysis/'+\ 'run_shrink_iondrift_4_c1/data/3DALL_t030322_060000.bin' path2 = '/home/guod/simulation_output/momentum_analysis/'+\ 'run_no_shrink_iondrift_4_1/data/3DALL_t030322_060000.bin' g1 = gitm.read(path1) g2 = gitm.read(path2) fig = plt.figure(figsize=(5.41, 8.54)) ax = fig.add_subplot(111, projection='3d') levels = [np.linspace(6.1e-10, 17.8e-10,21), np.linspace(1.1e-10, 2.7e-10, 21), np.linspace(1.3e-11, 3.9e-11,21), np.linspace(2.6e-12, 9.503e-12,21), np.linspace(4.3e-13, 2.71e-12,21), np.linspace(7.4e-14, 8.2e-13,21)] olat = -40 olatr = np.abs(olat)/180*np.pi glats, glons = convert(-90,0,0,date=dt.date(2003,3,22), a2g=True) glats, glons = glats/180*pi, glons/180*pi artalt = [10, 200, 380, 540, 680, 820] realalt = [150, 200, 300, 400, 500, 600] for ik, alt in enumerate([150, 200, 300, 400, 500, 600]): lon0, lat0, rho1 = g3ca.contour_data('Rho', g1, alt=alt) lon0, lat0, rho2 = g3ca.contour_data('Rho', g2, alt=alt) lat0, lon0 = lat0/180*pi, lon0/180*pi ilat = lat0[:, 0]<=olat/180*np.pi lat0, lon0, rho1, rho2 = \ lat0[ilat,:], lon0[ilat,:], rho1[ilat,:], rho2[ilat,:] r = lat0+pi/2 theta = lon0 x = r*np.cos(theta) x = -x # for sorthern hemisphere