Exemple #1
0
def plot_temperature():
    apex = Apex(date=2003)
    qlat, qlon = apex.convert(-90, 0, source='apex', dest='geo', height=400)

    plt.close('all')
    plt.figure(figsize=(7.26, 9.25))
    g = g2a
    alts = [130, 400]
    for ialt, alt in enumerate(alts):
        alt_ind = np.argmin(np.abs(g['Altitude'][0, 0, 2:-2]/1000-alt))+2
        alt_str = '%6.2f' % (g['Altitude'][0, 0, alt_ind]/1000)
        ax, projection = gcc.create_map(
                1, 2, ialt+1, 'polar', nlat=nlat, slat=slat, dlat=10,
                centrallon=g3ca.calculate_centrallon(g, 'polar',  useLT=True),
                coastlines=False)
        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, 21,
                         transform=ccrs.PlateCarree(), cmap='jet',
                         extend='both')
        hc = plt.colorbar(hc, pad=0.17)
        hc.set_label('Temperature (K)')
        ax.scatter(qlon, qlat, color='k', transform=ccrs.PlateCarree())
        plt.title('%s km' % alt_str, y=1.05)
    plt.text(0.5, 0.95, 'Time: '+titletime, fontsize=15,
            horizontalalignment='center', transform=plt.gcf().transFigure)
    plt.show()
    return
Exemple #2
0
    def satellite_position_lt_lat(self, mag=False, ns='N'):
        """ Show the lt and lat positions of the satellite in a polar
        coordinate.

        Input:
            mag: if True, for MLT and Mlat position
            ns: N or S for North and South hemispheres, respectively

        Output:
            hcup, hcdown: scatter handles for the up and down orbits,
                respectively.
        """
        if self.empty:
            return
        lt = self['LT']
        lat = self['lat']
        if mag:
            from apexpy import Apex
            gm = Apex()
            mlat, mlt = gm.convert(self['lat'],
                                   self['long'],
                                   'geo',
                                   'mlt',
                                   datetime=self.index)
            lt, lat = mlt, mlat
        ct = lat > 0 if ns is 'N' else lat < 0
        theta = lt[ct] / 12 * np.pi
        r = 90 - abs(lat[ct])
        hc = plt.scatter(theta, r, linewidths=0)
        return hc
Exemple #3
0
def test_basevectors_apex_array():
    A = Apex(date=2000, refh=300)
    f1, f2, f3, g1, g2, g3, d1, d2, d3, e1, e2, e3 = A.basevectors_apex([0, 30], 15, 100, coords='geo')
    _, _, _, _, f1_1, f2_1, _, d1_1, d2_1, d3_1, _, e1_1, e2_1, e3_1 = A._geo2apexall(0, 15, 100)
    _, _, _, _, f1_2, f2_2, _, d1_2, d2_2, d3_2, _, e1_2, e2_2, e3_2 = A._geo2apexall(30, 15, 100)

    assert_allclose(f1[:, 0], f1_1)
    assert_allclose(f2[:, 0], f2_1)
    assert_allclose(d1[:, 0], d1_1)
    assert_allclose(d2[:, 0], d2_1)
    assert_allclose(d3[:, 0], d3_1)
    assert_allclose(e1[:, 0], e1_1)
    assert_allclose(e2[:, 0], e2_1)
    assert_allclose(e3[:, 0], e3_1)

    assert_allclose(f3[:, 0], np.array([0.092637, -0.245951, 0.938848]), rtol=1e-4)
    assert_allclose(g1[:, 0], np.array([0.939012, 0.073416, -0.07342]), rtol=1e-4)
    assert_allclose(g2[:, 0], np.array([0.055389, 1.004155, 0.257594]), rtol=1e-4)
    assert_allclose(g3[:, 0], np.array([0, 0, 1.065135]), rtol=1e-4)

    assert_allclose(f1[:, 1], f1_2)
    assert_allclose(f2[:, 1], f2_2)
    assert_allclose(d1[:, 1], d1_2)
    assert_allclose(d2[:, 1], d2_2)
    assert_allclose(d3[:, 1], d3_2)
    assert_allclose(e1[:, 1], e1_2)
    assert_allclose(e2[:, 1], e2_2)
    assert_allclose(e3[:, 1], e3_2)

    assert_allclose(f3[:, 1], np.array([-0.036618, -0.071019, 0.861604]), rtol=1e-4)
    assert_allclose(g1[:, 1], np.array([0.844391, 0.015353, 0.037152]), rtol=1e-4)
    assert_allclose(g2[:, 1], np.array([0.050808, 1.02131, 0.086342]), rtol=1e-4)
    assert_allclose(g3[:, 1], np.array([0, 0, 1.160625]), rtol=1e-4)
Exemple #4
0
def test_mlt2mlon_range():
    A = Apex(date=2000, refh=300)
    assert_allclose(A.mlt2mlon(range(0, 25, 2), dt.datetime(2000, 2, 3, 4, 5, 6)),
                    [14.705551, 44.705551, 74.705551, 104.705551, 134.705551,
                     164.705551, 194.705551, 224.705551, 254.705551, 284.705551,
                     314.705551, 344.705551, 14.705551],
                    rtol=1e-4)
Exemple #5
0
    def satellite_position_lt_lat(self, mag=False, ns='N'):
        """ Show the lt and lat positions of the satellite in a polar
        coordinate.

        Input:
            mag: if True, for MLT and Mlat position
            ns: N or S for North and South hemispheres, respectively

        Output:
            hcup, hcdown: scatter handles for the up and down orbits,
                respectively.
        """
        if self.empty:
            return
        lt = self['LT']
        lat = self['lat']
        if mag:
            from apexpy import Apex
            gm = Apex()
            mlat,mlt = gm.convert(
                    self['lat'], self['long'], 'geo', 'mlt', datetime=self.index)
            lt, lat = mlt, mlat
        ct = lat>0 if ns is 'N' else lat<0
        theta = lt[ct]/12*np.pi
        r = 90 - abs(lat[ct])
        hc = plt.scatter(theta, r, linewidths=0)
        return hc
Exemple #6
0
def test_qd2geo():
    A = Apex(date=2000, refh=300)
    lat, lon, error = A.qd2geo(60, 15, 100, precision=1e-2)
    assert_allclose((lat, lon, error), A._qd2geo(60, 15, 100, 1e-2))
    assert type(lat) != np.ndarray
    assert type(lon) != np.ndarray
    assert type(error) != np.ndarray
Exemple #7
0
def func4():
    """
    Test (lat, lt) to (mlat, mlt) conversions.

    1, Use a = Apex(date=...); "date" determines which IGRF coefficients are
       used in conversions. Uses current date as default.
    2, height is needed for better conversion.
       champ and grace files use qd coordinates.
    3, mlt in qd and apex coordinates are the same.
    """
    import champ_grace as cg
    from apexpy import Apex as Apex
    import matplotlib.pyplot as plt
    a = cg.ChampDensity('2005-1-1', '2005-1-2')
    b = Apex(date=2005)
    mlatt, mlt = b.convert(
            lat=a.lat, lon=a.long, source='geo', dest='mlt',
            datetime=a.index, height=a.height)
    mlat, mlongt = b.convert(
            lat=a.lat, lon=a.long, source='geo', dest='qd',
            height=a.height)
    mlat2 = np.array(a.Mlat)
    mlt2 = np.array(a.MLT)
    plt.plot(mlat-mlat2)
    plt.plot(abs(mlt-mlt2) % 24, '.')
    plt.show()
    return
Exemple #8
0
def plot_ion_drift(show=True,save=True):
    apex = Apex(date=2003)
    qlat, qlon = apex.convert(-90, 0, source='apex', dest='geo', height=400)
    g = g2a

    plt.close('all')
    plt.figure(figsize=(7.26, 9.25))
    for ialt, alt in enumerate([130, 200, 300, 400, 500, 600]):
        alt_ind = np.argmin(np.abs(g['Altitude'][0, 0, :]/1000-alt))
        alt_str = '%6.2f' % (g['Altitude'][0, 0, alt_ind]/1000)
        ax, projection = gcc.create_map(
                3, 2, ialt+1, 'polar', nlat=nlat, slat=slat, dlat=10,
                centrallon=g3ca.calculate_centrallon(g, 'polar',  useLT=True),
                coastlines=False)
        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)
        hq = ax.quiver(
                lon0, lat0, ewind, nwind, scale=1500, scale_units='inches',
                regrid_shape=20, headwidth=5)
        ax.quiverkey(hq, 0.93, -0.1, 1000, '1000 m/s')
        ax.scatter(qlon, qlat, color='k', transform=ccrs.PlateCarree())
        plt.title('%s km' % alt_str, y=1.05)
    plt.text(0.5, 0.95, 'Time: '+tstring, fontsize=15,
            horizontalalignment='center', transform=plt.gcf().transFigure)
    if show:
        plt.show()
    if save:
        plt.savefig(spath+'03_ion_drift_%s%s.pdf' % (tstrday,tstring))
    return
Exemple #9
0
def test_basevectors_apex_scalar_shape():
    A = Apex(date=2000, refh=300)
    ret = A.basevectors_apex(60, 15, 100, precision=1e-2)
    for r in ret[:2]:
        assert r.shape == (2,)
    for r in ret[2:]:
        assert r.shape == (3,)
Exemple #10
0
def process_interval(start_date, end_date, hemisphere, output_fn, input_dir, mlt_vals, sample_dt):
    logger.info(f"processing arb data for {start_date, end_date}")
    ref_times = np.arange(np.datetime64(start_date, 's'), np.datetime64(end_date, 's') + sample_dt, sample_dt)
    apex = Apex(date=start_date)
    arb_data, times = _get_downloaded_arb_data(start_date, end_date, input_dir)
    if times.size == 0 or min(times) > ref_times[0] or max(times) < ref_times[-1]:
        logger.error(f"times size: {times.size}")
        if len(times) > 0:
            logger.error(f"{min(times)=} {ref_times[0]=} {max(times)=} {ref_times[-1]=}")
        raise InvalidProcessDates("Need to download full data range before processing")
    logger.info(f"{times.shape[0]} time points")
    sort_idx = np.argsort(times)

    mlat = np.empty((times.shape[0], mlt_vals.shape[0]))
    for i, idx in enumerate(sort_idx):
        height = np.mean(arb_data['ALTITUDE'][idx])
        lat = arb_data[f'MODEL_{hemisphere.upper()}_GEOGRAPHIC_LATITUDE'][idx]
        lon = arb_data[f'MODEL_{hemisphere.upper()}_GEOGRAPHIC_LONGITUDE'][idx]
        apx_lat, mlt = apex.convert(lat, lon, 'geo', 'mlt', height, utils.datetime64_to_datetime(times[idx]))
        mlat[i] = np.interp(mlt_vals, mlt, apx_lat, period=24)
    good_mask = np.mean(abs(mlat - np.median(mlat, axis=0, keepdims=True)), axis=1) < 1
    interpolator = interp1d(
        times.astype('datetime64[s]').astype(float)[sort_idx][good_mask],
        mlat[good_mask],
        axis=0, bounds_error=False
    )
    mlat = interpolator(ref_times.astype(float))
    data = xr.DataArray(
        mlat,
        coords={'time': ref_times, 'mlt': mlt_vals},
        dims=['time', 'mlt']
    )
    logger.info(f"ref times: [{ref_times[0]}, {ref_times[-1]}]")
    data.to_netcdf(output_fn)
Exemple #11
0
def test_basevectors_apex_vectorization_height():
    A = Apex(date=2000, refh=0)
    f1, f2, f3, g1, g2, g3, d1, d2, d3, e1, e2, e3 = A.basevectors_apex(60, 15, [200, 400], coords='geo')
    _, _, _, _, f1_1, f2_1, _, d1_1, d2_1, d3_1, _, e1_1, e2_1, e3_1 = A._geo2apexall(60, 15, 200)
    _, _, _, _, f1_2, f2_2, _, d1_2, d2_2, d3_2, _, e1_2, e2_2, e3_2 = A._geo2apexall(60, 15, 400)

    assert_allclose(f1[:, 0], f1_1)
    assert_allclose(f2[:, 0], f2_1)
    assert_allclose(d1[:, 0], d1_1)
    assert_allclose(d2[:, 0], d2_1)
    assert_allclose(d3[:, 0], d3_1)
    assert_allclose(e1[:, 0], e1_1)
    assert_allclose(e2[:, 0], e2_1)
    assert_allclose(e3[:, 0], e3_1)

    assert_allclose(f3[:, 0], np.array([-0.088671, -0.018272, 0.993576]), rtol=1e-4)
    assert_allclose(g1[:, 0], np.array([0.903098, 0.245273, 0.085107]), rtol=1e-4)
    assert_allclose(g2[:, 0], np.array([-0.103495, 1.072078, 0.01048]), rtol=1e-4)
    assert_allclose(g3[:, 0], np.array([0, 0, 1.006465]), rtol=1e-4)

    assert_allclose(f1[:, 1], f1_2)
    assert_allclose(f2[:, 1], f2_2)
    assert_allclose(d1[:, 1], d1_2)
    assert_allclose(d2[:, 1], d2_2)
    assert_allclose(d3[:, 1], d3_2)
    assert_allclose(e1[:, 1], e1_2)
    assert_allclose(e2[:, 1], e2_2)
    assert_allclose(e3[:, 1], e3_2)

    assert_allclose(f3[:, 1], np.array([-0.085415, -0.021176, 0.989645]), rtol=1e-4)
    assert_allclose(g1[:, 1], np.array([0.902695, 0.246919, 0.083194]), rtol=1e-4)
    assert_allclose(g2[:, 1], np.array([-0.11051, 1.066094, 0.013274]), rtol=1e-4)
    assert_allclose(g3[:, 1], np.array([0, 0, 1.010463]), rtol=1e-4)
Exemple #12
0
def test_geo2apex_undefined_warning():
    apex_out = Apex(date=2000, refh=10000)
    with warnings.catch_warnings(record=True) as w:
        ret = apex_out.geo2apex(0, 0, 0)
        assert ret[0] == -9999
        assert issubclass(w[-1].category, UserWarning)
        assert 'set to -9999 where' in str(w[-1].message)
Exemple #13
0
def test_qd2geo():
    apex_out = Apex(date=2000, refh=300)
    lat, lon, error = apex_out.qd2geo(60, 15, 100, precision=1e-2)
    assert_allclose((lat, lon, error), apex_out._qd2geo(60, 15, 100, 1e-2))
    assert type(lat) != np.ndarray
    assert type(lon) != np.ndarray
    assert type(error) != np.ndarray
Exemple #14
0
def test_mlon2mlt_range():
    A = Apex(date=2000, refh=300)
    assert_allclose(A.mlon2mlt(range(0, 361, 30), dt.datetime(2000, 2, 3, 4, 5, 6)),
                    [23.01963, 1.01963, 3.01963, 5.01963, 7.01963,
                     9.01963, 11.01963, 13.01963, 15.01963, 17.01963,
                     19.01963, 21.01963, 23.01963],
                    rtol=1e-4)
Exemple #15
0
def test__qd2geo_scalar():
    apex_out = Apex(date=2000, refh=300)
    for lat in [0, 30, 60, 89]:
        for lon in [-179, -90, 0, 90, 180]:
            for prec in [-1, 1e-2, 1e-10]:
                assert_allclose(apex_out._qd2geo(lat, lon, 100, prec),
                                fa.apxq2g(lat, lon, 100, prec))
Exemple #16
0
def test_qd2apex():
    A = Apex(date=2000, refh=300)
    lat, lon = A.qd2apex(60, 15, 100)
    assert_allclose((lat, lon),
                    [59.491381, 15])
    assert type(lat) != np.ndarray
    assert type(lon) != np.ndarray
Exemple #17
0
def test_basevectors_apex_scalar_shape():
    apex_out = Apex(date=2000, refh=300)
    ret = apex_out.basevectors_apex(60, 15, 100, precision=1e-2)
    for r in ret[:2]:
        assert r.shape == (2, )
    for r in ret[2:]:
        assert r.shape == (3, )
Exemple #18
0
def test_apex2qd():
    A = Apex(date=2000, refh=300)
    lat, lon = A.apex2qd(60, 15, 100)
    assert_allclose((lat, lon),
                    [60.498401, 15])
    assert type(lat) != np.ndarray
    assert type(lon) != np.ndarray
Exemple #19
0
def test_mlt2mlon_offset():
    apex_out = Apex(date=2000, refh=300)
    date = dt.datetime(2000, 2, 3, 4, 5, 6)
    assert_allclose(apex_out.mlt2mlon(0, date),
                    apex_out.mlt2mlon(1, date) - 15)
    assert_allclose(apex_out.mlt2mlon(0, date),
                    apex_out.mlt2mlon(10, date) - 150)
Exemple #20
0
def test__geo2qd_longitude():
    A = Apex(date=2000, refh=300)
    assert_allclose(A._geo2qd(60, 180, 100), fa.apxg2q(60, 180, 100, 0)[:2])
    assert_allclose(A._geo2qd(60, -180, 100), fa.apxg2q(60, -180, 100, 0)[:2])
    assert_allclose(A._geo2qd(60, -180, 100), A._geo2qd(60, 180, 100))
    for i in range(-5, 5):
        for lat in [0, 30, 60, 90]:
            assert_allclose(A._geo2qd(lat, 15+i*360, 100), fa.apxg2q(lat, 15, 100, 0)[:2])
Exemple #21
0
def test_mlon2mlt_range():
    apex_out = Apex(date=2000, refh=300)
    assert_allclose(apex_out.mlon2mlt(range(
        0, 361, 30), dt.datetime(2000, 2, 3, 4, 5, 6)), [
            23.01963, 1.01963, 3.01963, 5.01963, 7.01963, 9.01963, 11.01963,
            13.01963, 15.01963, 17.01963, 19.01963, 21.01963, 23.01963
        ],
                    rtol=1e-4)
Exemple #22
0
def test_map_to_height_conjugate():
    A = Apex(date=2000, refh=300)
    assert_allclose(
        A.map_to_height(60, 15, 100, 10000, conjugate=True, precision=1e-10),
        (-25.424892425537109, 27.310417175292969, 1.2074182222931995e-6))
    assert_allclose(
        A.map_to_height(30, 170, 100, 500, conjugate=True, precision=1e-2),
        (-13.76642894744873, 164.24259948730469, 0.00056820799363777041))
Exemple #23
0
def test__qd2geo_longitude():
    A = Apex(date=2000, refh=300)
    assert_allclose(A._qd2geo(60, 180, 100, 1e-2), fa.apxq2g(60, 180, 100, 1e-2))
    assert_allclose(A._qd2geo(60, -180, 100, 1e-2), fa.apxq2g(60, -180, 100, 1e-2))
    assert_allclose(A._qd2geo(60, -180, 100, 1e-2), A._qd2geo(60, 180, 100, 1e-2))
    for i in range(-5, 5):
        for lat in [0, 30, 60, 90]:
            assert_allclose(A._qd2geo(lat, 15+i*360, 100, 1e-2), fa.apxq2g(lat, 15, 100, 1e-2))
Exemple #24
0
def test__geo2apexall_scalar():
    apex_out = Apex(date=2000, refh=300)
    for lat in [0, 30, 60, 89]:
        for lon in [-179, -90, 0, 90, 180]:
            ret1 = apex_out._geo2apexall(lat, lon, 100)
            ret2 = fa.apxg2all(lat, lon, 100, 300, 1)
            for r1, r2 in zip(ret1, ret2):
                assert_allclose(r1, r2)
Exemple #25
0
def test_mlt2mlon2mlt():
    apex_out = Apex(date=2000, refh=300)
    date = dt.datetime(2000, 2, 3, 4, 5, 6)
    assert_allclose(apex_out.mlt2mlon(apex_out.mlon2mlt(0, date), date), 0)
    assert_allclose(apex_out.mlt2mlon(apex_out.mlon2mlt(90, date), date), 90)
    assert_allclose(apex_out.mlt2mlon(apex_out.mlon2mlt(180, date), date), 180)
    assert_allclose(apex_out.mlt2mlon(apex_out.mlon2mlt(270, date), date), 270)
    assert_allclose(apex_out.mlt2mlon(apex_out.mlon2mlt(360, date), date), 0)
Exemple #26
0
def test_map_to_height():
    A = Apex(date=2000, refh=300)
    assert_allclose(
        A.map_to_height(60, 15, 100, 10000, conjugate=False, precision=1e-10),
        (31.841459274291992, 17.916629791259766, 0))
    assert_allclose(
        A.map_to_height(30, 170, 100, 500, conjugate=False, precision=1e-2),
        (25.727252960205078, 169.60546875, 0.00017655163537710905))
Exemple #27
0
def test__geo2apexall_scalar():
    A = Apex(date=2000, refh=300)
    for lat in [0, 30, 60, 89]:
        for lon in [-179, -90, 0, 90, 180]:
            ret1 = A._geo2apexall(lat, lon, 100)
            ret2 = fa.apxg2all(lat, lon, 100, 300, 1)
            for r1, r2 in zip(ret1, ret2):
                assert_allclose(r1, r2)
Exemple #28
0
def test__basevec_longitude():
    A = Apex(date=2000, refh=300)
    assert_allclose(A._basevec(60, 180, 100), fa.apxg2q(60, 180, 100, 1)[2:4])
    assert_allclose(A._basevec(60, -180, 100), fa.apxg2q(60, -180, 100, 1)[2:4])
    assert_allclose(A._basevec(60, -180, 100), A._basevec(60, 180, 100))
    for i in range(-5, 5):
        for lat in [0, 30, 60, 90]:
            assert_allclose(A._basevec(lat, 15+i*360, 100), fa.apxg2q(lat, 15, 100, 1)[2:4])
Exemple #29
0
def magConjugated(glat, glon, galtkm, conj_galtkm=None):
    if conj_galtkm is None:
        conj_galtkm = galtkm
    A = Apex()
    mlat, mlon = A.convert(lon=np.unwrap(glon, 180), lat = glat, source='geo', dest='apex', height = galtkm)
    Cglat, Cglon = A.convert(lat=-mlat, lon=mlon, source='apex', dest='geo', height = conj_galtkm)
    
    return Cglat, Cglon
Exemple #30
0
def test_basevectors_qd_array():
    A = Apex(date=2000, refh=300)
    f1, f2 = A.basevectors_qd([0, 30], 15, 100, coords='geo')
    f1_lat0, f2_lat0 = A._basevec(0, 15, 100)
    f1_lat30, f2_lat30 = A._basevec(30, 15, 100)
    assert_allclose(f1[:, 0], f1_lat0)
    assert_allclose(f2[:, 0], f2_lat0)
    assert_allclose(f1[:, 1], f1_lat30)
    assert_allclose(f2[:, 1], f2_lat30)
Exemple #31
0
def test_basevectors_qd_array():
    apex_out = Apex(date=2000, refh=300)
    f1, f2 = apex_out.basevectors_qd([0, 30], 15, 100, coords='geo')
    f1_lat0, f2_lat0 = apex_out._basevec(0, 15, 100)
    f1_lat30, f2_lat30 = apex_out._basevec(30, 15, 100)
    assert_allclose(f1[:, 0], f1_lat0)
    assert_allclose(f2[:, 0], f2_lat0)
    assert_allclose(f1[:, 1], f1_lat30)
    assert_allclose(f2[:, 1], f2_lat30)
Exemple #32
0
def test__geo2apex_array():
    A = Apex(date=2000, refh=300)
    lats, lons = A._geo2apex([[0, 30], [60, 90]], 15, [[100, 200], [300, 400]])
    lat1, lon1 = fa.apxg2all(0, 15, 100, 300, 0)[2:4]
    lat2, lon2 = fa.apxg2all(30, 15, 200, 300, 0)[2:4]
    lat3, lon3 = fa.apxg2all(60, 15, 300, 300, 0)[2:4]
    lat4, lon4 = fa.apxg2all(90, 15, 400, 300, 0)[2:4]
    assert_allclose(lats.astype(float), np.array([[lat1, lat2], [lat3, lat4]], dtype=float))
    assert_allclose(lons.astype(float), np.array([[lon1, lon2], [lon3, lon4]], dtype=float))
Exemple #33
0
def test_mlt2mlon_range():
    apex_out = Apex(date=2000, refh=300)
    assert_allclose(apex_out.mlt2mlon(range(
        0, 25, 2), dt.datetime(2000, 2, 3, 4, 5, 6)), [
            14.705551, 44.705551, 74.705551, 104.705551, 134.705551,
            164.705551, 194.705551, 224.705551, 254.705551, 284.705551,
            314.705551, 344.705551, 14.705551
        ],
                    rtol=1e-4)
Exemple #34
0
def test_geo2apex_undefined_warning():
    A = Apex(date=2000, refh=10000)
    with warnings.catch_warnings(record=True) as w:
        ret = A.geo2apex(0, 0, 0)
        A.geo2apex(0, 0, 0)
        assert ret[0] == -9999
        assert len(w) == 2
        assert issubclass(w[-1].category, UserWarning)
        assert 'set to -9999 where' in str(w[-1].message)
Exemple #35
0
def test_set_refh():
    A = Apex(date=2000, refh=300)
    assert A.refh, 300
    ret_300 = A._geo2apex(60, 15, 100)
    A.set_refh(500)
    assert A.refh == 500
    ret_500 = A._geo2apex(60, 15, 100)

    assert_allclose(ret_300, fa.apxg2all(60, 15, 100, 300, 0)[2:4])
    assert_allclose(ret_500, fa.apxg2all(60, 15, 100, 500, 0)[2:4])
Exemple #36
0
def test_apex2geo():
    A = Apex(date=2000, refh=300)
    lat, lon, error = A.apex2geo(60, 15, 100, precision=1e-2)
    assert_allclose((lat, lon, error),
                    A.qd2geo(*A.apex2qd(60, 15, 100),
                             height=100,
                             precision=1e-2))
    assert type(lat) != np.ndarray
    assert type(lon) != np.ndarray
    assert type(error) != np.ndarray
Exemple #37
0
def test__qd2geo_array():
    A = Apex(date=2000, refh=300)
    lats, lons, errs = A._qd2geo([[0, 30], [60, 90]], 15, [[100, 200], [300, 400]], 1e-2)
    lat1, lon1, err1 = fa.apxq2g(0, 15, 100, 1e-2)
    lat2, lon2, err2 = fa.apxq2g(30, 15, 200, 1e-2)
    lat3, lon3, err3 = fa.apxq2g(60, 15, 300, 1e-2)
    lat4, lon4, err4 = fa.apxq2g(90, 15, 400, 1e-2)
    assert_allclose(lats.astype(float), np.array([[lat1, lat2], [lat3, lat4]], dtype=float))
    assert_allclose(lons.astype(float), np.array([[lon1, lon2], [lon3, lon4]], dtype=float))
    assert_allclose(errs.astype(float), np.array([[err1, err2], [err3, err4]], dtype=float))
Exemple #38
0
def test_map_to_height_same_height():
    apex_out = Apex(date=2000, refh=300)
    assert_allclose(apex_out.map_to_height(60,
                                           15,
                                           100,
                                           100,
                                           conjugate=False,
                                           precision=1e-10),
                    (60, 15, 3.4150946248701075e-6),
                    rtol=1e-5)
Exemple #39
0
def plot_vert_vgradrho_rho_diff(show=True, save=True):
    rho1 = np.array(g1a['Rho'])
    vgradrho1 = \
        g1a['V!Dn!N (up)'] \
        * cr.calc_rusanov_alts_ausm(g1a['Altitude'],rho1)/g1a['Rho']

    rho2 = np.array(g2a['Rho'])
    vgradrho2 = \
        g2a['V!Dn!N (up)']\
        * cr.calc_rusanov_alts_ausm(g2a['Altitude'],rho2)/g2a['Rho']

    g1a['vgradrho_diff'] = vgradrho1-vgradrho2

    apex = Apex(date=2003)
    qlat, qlon = apex.convert(-90, 0, source='apex', dest='geo', height=400)

    plt.close('all')
    plt.figure(figsize=(7.26, 9.25))
    for ialt, alt in enumerate([130, 200, 300, 400, 500, 600]):
        alt_ind = np.argmin(np.abs(g1a['Altitude'][0, 0, :]/1000-alt))
        alt_str = '%6.2f' % (g1a['Altitude'][0, 0, alt_ind]/1000)
        ax, projection = gcc.create_map(
            3, 2, ialt+1, 'polar', nlat=nlat, slat=slat, dlat=10,
            centrallon=g3ca.calculate_centrallon(g1a, 'polar',  useLT=True),
            coastlines=False)
        lon0, lat0, zdata0 = g3ca.contour_data('vgradrho_diff', g1a, alt=alt)
        fp = (lat0[:,0]>slat) & (lat0[:,0]<nlat)
        lon0, lat0, zdata0 = lon0[fp, :], lat0[fp,:], zdata0[fp,:]
        hc = ax.contourf(
            lon0, lat0, zdata0, np.linspace(-1,1,21)*1e-4,
            transform=ccrs.PlateCarree(), cmap='seismic', extend='both')
        hcb = plt.colorbar(hc, pad=0.17)
        hcb.formatter.set_powerlimits((0,0))
        hcb.update_ticks()
        hcb.set_label(r'$-\vec{u}\cdot\frac{\nabla\rho}{\rho}$ (up)')
        # wind difference
        lon1, lat1, ewind1, nwind1 = g3ca.vector_data(g1a, 'neutral', alt=alt)
        lon2, lat2, ewind2, nwind2 = g3ca.vector_data(g2a, 'neutral', alt=alt)
        lon0, lat0 = lon1, lat1
        lon0, lat0, ewind0, nwind0 = g3ca.convert_vector(
            lon0, lat0, ewind2-ewind1, nwind2-nwind1, 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.93, -0.1, 500, '500 m/s')
        ax.scatter(qlon, qlat, color='k', transform=ccrs.PlateCarree())
        plt.title('%s km' % alt_str, y=1.05)
    plt.text(0.5, 0.95, 'Time: '+tstring, fontsize=15,
            horizontalalignment='center', transform=plt.gcf().transFigure)
    if show:
        plt.show()
    if save:
        plt.savefig(spath+'06_vert_vgradrho_rho_diff_%s%s.pdf' % (tstrday,tstring))
    return
Exemple #40
0
def test_convert_mlt2apex():
    datetime = dt.datetime(2000, 3, 9, 14, 25, 58)
    A = Apex(date=2000, refh=300)
    assert_allclose(
        A.convert(60,
                  15,
                  'mlt',
                  'apex',
                  height=100,
                  datetime=datetime,
                  ssheight=2e5), (60, A.mlt2mlon(15, datetime, ssheight=2e5)))
Exemple #41
0
def test__geo2qd_array():
    A = Apex(date=2000, refh=300)
    lats, lons = A._geo2qd([[0, 30], [60, 90]], 15, [[100, 200], [300, 400]])
    lat1, lon1 = fa.apxg2q(0, 15, 100, 0)[:2]
    lat2, lon2 = fa.apxg2q(30, 15, 200, 0)[:2]
    lat3, lon3 = fa.apxg2q(60, 15, 300, 0)[:2]
    lat4, lon4 = fa.apxg2q(90, 15, 400, 0)[:2]
    assert_allclose(lats.astype(float),
                    np.array([[lat1, lat2], [lat3, lat4]], dtype=float))
    assert_allclose(lons.astype(float),
                    np.array([[lon1, lon2], [lon3, lon4]], dtype=float))
Exemple #42
0
def test_basevectors_qd_vectorization():
    apex_out = Apex(date=2000, refh=300)
    ret = apex_out.basevectors_qd([60, 60, 60, 60], 15, 100, coords='geo')
    for r in ret:
        assert r.shape == (2, 4)
    ret = apex_out.basevectors_qd(60, [15, 15, 15, 15], 100, coords='geo')
    for r in ret:
        assert r.shape == (2, 4)
    ret = apex_out.basevectors_qd(60, 15, [100, 100, 100, 100], coords='geo')
    for r in ret:
        assert r.shape == (2, 4)
Exemple #43
0
def plot_vert_vgradrho_rho_diff(show=True, save=True):
    rho1 = np.array(g1a['Rho'])
    vgradrho1 = \
        g1a['V!Dn!N (up)']\
        *cr.calc_rusanov_alts_ausm(g1a['Altitude'],rho1)/g1a['Rho']

    rho2 = np.array(g2a['Rho'])
    vgradrho2 = \
        g2a['V!Dn!N (up)']\
        *cr.calc_rusanov_alts_ausm(g2a['Altitude'],rho2)/g2a['Rho']

    g1a['vgradrho_diff'] = vgradrho1-vgradrho2

    apex = Apex(date=2003)
    qlat, qlon = apex.convert(-90, 0, source='apex', dest='geo', height=400)

    plt.close('all')
    #plt.figure(figsize=(7.26, 9.25))
    plt.figure(figsize=(8.97, 3.45))
    alts = [130, 400]
    for ialt, alt in enumerate(alts):
        alt_ind = np.argmin(np.abs(g1a['Altitude'][0, 0, :]/1000-alt))
        alt_str = '%6.2f' % (g1a['Altitude'][0, 0, alt_ind]/1000)
        ax, projection = gcc.create_map(
            1, 2, ialt+1, 'polar', nlat=nlat, slat=slat, dlat=10,
            centrallon=g3ca.calculate_centrallon(g1a, 'polar',  useLT=True),
            coastlines=False)
        lon0, lat0, zdata0 = g3ca.contour_data('vgradrho_diff', g1a, alt=alt)
        fp = (lat0[:,0]>slat) & (lat0[:,0]<nlat)
        lon0, lat0, zdata0 = lon0[fp, :], lat0[fp,:], zdata0[fp,:]
        hc = ax.contourf(
            lon0, lat0, zdata0, np.linspace(-1,1,21)*1e-4,
            transform=ccrs.PlateCarree(), cmap='seismic', extend='both')
        hcb = plt.colorbar(hc, pad=0.17)
        hcb.formatter.set_powerlimits((0,0))
        hcb.update_ticks()
        hcb.set_label(r'$-\vec{u}\cdot\frac{\nabla\rho}{\rho}$ (up)')

        # lon1, lat1, ewind1, nwind1 = g3ca.vector_data(g1a, 'neutral', alt=alt)
        # lon2, lat2, ewind2, nwind2 = g3ca.vector_data(g2a, 'neutral', alt=alt)
        # lon0, lat0 = lon1, lat1
        # lon0, lat0, ewind0, nwind0 = g3ca.convert_vector(
        #         lon0, lat0, ewind2-ewind1, nwind2-nwind1, 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.93, -0.1, 300, '500 m/s')
        ax.scatter(qlon, qlat, color='k', transform=ccrs.PlateCarree())
        plt.title('%s km' % alt_str, y=1.05)
    plt.text(0.5, 0.95, 'Time: '+titletime, fontsize=15,
            horizontalalignment='center', transform=plt.gcf().transFigure)
    plt.show()
    return
Exemple #44
0
def test_basevectors_qd_vectorization():
    A = Apex(date=2000, refh=300)
    ret = A.basevectors_qd([60, 60, 60, 60], 15, 100, coords='geo')
    for r in ret:
        assert r.shape == (2, 4)
    ret = A.basevectors_qd(60, [15, 15, 15, 15], 100, coords='geo')
    for r in ret:
        assert r.shape == (2, 4)
    ret = A.basevectors_qd(60, 15, [100, 100, 100, 100], coords='geo')
    for r in ret:
        assert r.shape == (2, 4)
Exemple #45
0
def test_convert_qd2mlt():
    datetime = dt.datetime(2000, 3, 9, 14, 25, 58)
    A = Apex(date=2000, refh=300)
    assert_allclose(
        A.convert(60,
                  15,
                  'qd',
                  'mlt',
                  height=100,
                  datetime=datetime,
                  ssheight=2e5)[1], A.mlon2mlt(15, datetime, ssheight=2e5))
Exemple #46
0
def test_mlt2mlon2mlt():
    A = Apex(date=2000, refh=300)
    date = dt.datetime(2000, 2, 3, 4, 5, 6)
    assert_allclose(A.mlt2mlon(A.mlon2mlt(0, date), date), 0)
    assert_allclose(A.mlt2mlon(A.mlon2mlt(90, date), date), 90)
    assert_allclose(A.mlt2mlon(A.mlon2mlt(180, date), date), 180)
    assert_allclose(A.mlt2mlon(A.mlon2mlt(270, date), date), 270)
    assert_allclose(A.mlt2mlon(A.mlon2mlt(360, date), date), 0)
Exemple #47
0
def test_convert_geo2mlt():
    datetime = dt.datetime(2000, 3, 9, 14, 25, 58)
    A = Apex(date=2000, refh=300)
    assert_allclose(
        A.convert(60,
                  15,
                  'geo',
                  'mlt',
                  height=100,
                  ssheight=2e5,
                  datetime=datetime)[1],
        A.mlon2mlt(A.geo2apex(60, 15, 100)[1], datetime, ssheight=2e5))
Exemple #48
0
def plot_temperature_diff(show=True, save=True):
    apex = Apex(date=2003)
    qlat, qlon = apex.convert(-90, 0, source='apex', dest='geo', height=400)

    plt.close('all')
    plt.figure(figsize=(7.26, 9.25))
    for ialt, alt in enumerate([130, 200, 300, 400, 500, 600]):
        alt_ind = np.argmin(np.abs(g1a['Altitude'][0, 0, :]/1000-alt))
        alt_str = '%6.2f' % (g1a['Altitude'][0, 0, alt_ind]/1000)
        ax, projection = gcc.create_map(
            3, 2, ialt+1, 'polar', nlat=nlat, slat=slat, dlat=10,
            centrallon=g3ca.calculate_centrallon(g1a, 'polar',  useLT=True),
            coastlines=False)
        # temperature diff
        lon1, lat1, zdata1 = g3ca.contour_data('Temperature', g1a, alt=alt)
        lon2, lat2, zdata2 = g3ca.contour_data('Temperature', g2a, alt=alt)
        fp = (lat1[:,0]>slat) & (lat1[:,0]<nlat)
        lon0, lat0, zdata0 = lon1[fp, :], lat1[fp,:], (zdata2-zdata1)[fp,:]
        hc = ax.contourf(
            lon0, lat0, zdata0, np.linspace(-80,80,21),
            transform=ccrs.PlateCarree(), cmap='seismic', extend='both')
        hc = plt.colorbar(hc, pad=0.17)
        hc.set_label(r'$T_2-T_1$ (K)')
        # geomagnetic pole
        ax.scatter(qlon, qlat, color='k', transform=ccrs.PlateCarree())

        # wind difference
        lon1, lat1, ewind1, nwind1 = g3ca.vector_data(g1a, 'neutral', alt=alt)
        lon2, lat2, ewind2, nwind2 = g3ca.vector_data(g2a, 'neutral', alt=alt)
        lon0, lat0 = lon1, lat1
        lon0, lat0, ewind0, nwind0 = g3ca.convert_vector(
            lon0, lat0, ewind2-ewind1, nwind2-nwind1, 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.93, -0.1, 500, '500 m/s')

        # rho difference
        #lon3, lat3, zdata3 = g3ca.contour_data('Rho', g1a, alt=alt)
        #lon4, lat4, zdata4 = g3ca.contour_data('Rho', g2a, alt=alt)
        #diffrho = 100*(zdata4-zdata3)/zdata3
        #hc = ax.contour(
        #        lon4, lat4, diffrho, [-10], transform=ccrs.PlateCarree(),
        #        colors='g',linestyles='-')
        plt.title('%s km' % alt_str, y=1.05)
    plt.text(0.5, 0.95, 'Time: '+tstring, fontsize=15,
            horizontalalignment='center', transform=plt.gcf().transFigure)
    if show:
        plt.show()
    if save:
        plt.savefig(spath+'02_temperature_diff_%s%s.pdf' % (tstrday,tstring))
    return
def map_vec(alt):
    # calculates plasma drift velocity and electric field vectors in geodetic components at a particular altitude

    VE, E, mlat, mlon = read_vvels_file('test_vvels.h5')
    A = Apex(2019)
    f1, f2, f3, g1, g2, g3, d1, d2, d3, e1, e2, e3 = A.basevectors_apex(
        mlat, mlon, alt, coords='apex')

    VEgd = (VE[:, 0] * e1 + VE[:, 1] * e2 + VE[:, 2] * e3).T
    Egd = (E[:, 0] * d1 + E[:, 1] * e2 + E[:, 2] * e3).T

    return VEgd, Egd
Exemple #50
0
def test__geo2apex_array():
    apex_out = Apex(date=2000, refh=300)
    lats, lons = apex_out._geo2apex([[0, 30], [60, 90]], 15,
                                    [[100, 200], [300, 400]])
    lat1, lon1 = fa.apxg2all(0, 15, 100, 300, 0)[2:4]
    lat2, lon2 = fa.apxg2all(30, 15, 200, 300, 0)[2:4]
    lat3, lon3 = fa.apxg2all(60, 15, 300, 300, 0)[2:4]
    lat4, lon4 = fa.apxg2all(90, 15, 400, 300, 0)[2:4]
    assert_allclose(lats.astype(float),
                    np.array([[lat1, lat2], [lat3, lat4]], dtype=float))
    assert_allclose(lons.astype(float),
                    np.array([[lon1, lon2], [lon3, lon4]], dtype=float))
Exemple #51
0
def test_convert_apex2mlt():
    datetime = dt.datetime(2000, 3, 9, 14, 25, 58)
    apex_out = Apex(date=2000, refh=300)
    assert_allclose(
        apex_out.convert(60,
                         15,
                         'apex',
                         'mlt',
                         height=100,
                         datetime=datetime,
                         ssheight=2e5)[1],
        apex_out.mlon2mlt(15, datetime, ssheight=2e5))
Exemple #52
0
    def satellite_position_lt_lat(self,
                                  ax,
                                  nlat=90,
                                  slat=0,
                                  mag=False,
                                  plot_type='polar',
                                  *args,
                                  **kwargs):
        """ Show the (M)lt and (M)lat positions of the satellite in a polar
        or rectangular coordinate axis.

        Input:
            ax: which axis to draw orbit on
            nlat: northward latitude limit (default 90)
            slat: southward latitude limit (default 0)
            mag: if True, for MLT and Mlat position
        Return:
            hc: handle of the scatter
        """
        if self.empty:
            return
        tmp = self
        if mag:
            from apexpy import Apex
            import datetime as dt
            a = Apex(date=self.index.year.mean())
            mlat, mlt = a.convert(tmp.lat,
                                  tmp.long,
                                  'geo',
                                  'mlt',
                                  height=tmp.height,
                                  datetime=tmp.index)
            tmp['MLT'] = mlt
            tmp['Mlat'] = mlat
        ltp = 'MLT' if mag else 'LT'
        latp = 'Mlat' if mag else 'lat'
        ct = (self[latp] > slat) & (self[latp] < nlat)
        if 'pol' in plot_type.lower():
            if nlat * slat < 0:
                print('Error: For polar plot, nlat and slat'
                      ' should have the same signs')
            csign = 1 if nlat > 0 else -1
            theta = tmp.loc[ct, ltp] / 12 * np.pi
            r = 90 - csign * tmp.loc[ct, latp]
            hc = ax.scatter(theta, r, linewidths=0, *args, **kwargs)
        if 'rec' in plot_type.lower():
            hc = ax.scatter(tmp.loc[ct, ltp],
                            tmp.loc[ct, latp],
                            linewidths=0,
                            *args,
                            **kwargs)
        return hc
Exemple #53
0
def test_basevectors_apex_delta():
    A = Apex(date=2000, refh=300)
    for lat in range(0, 90, 10):
        for lon in range(0, 360, 15):
            f1, f2, f3, g1, g2, g3, d1, d2, d3, e1, e2, e3 = A.basevectors_apex(lat, lon, 500)
            f = [np.append(f1, 0), np.append(f2, 0), f3]
            g = [g1, g2, g3]
            d = [d1, d2, d3]
            e = [e1, e2, e3]
            for i, j in [(i, j) for i in range(3) for j in range(3)]:
                delta = 1 if i == j else 0
                assert_allclose(np.sum(f[i]*g[j]), delta, rtol=0, atol=1e-5)
                assert_allclose(np.sum(d[i]*e[j]), delta, rtol=0, atol=1e-5)
Exemple #54
0
def pole_unit_vector(t):
    """credit: Eelco Doornbos"""
    apexdate = t.year + t.dayofyear / 365  # routine needs data as for example 2015.3
    A = Apex(date=apexdate)
    glat, glon = A.convert(90, 0, 'apex', 'geo', height=0)
    colatrad = radians(90.0 - glat)
    lonrad = radians(glon)

    return np.array([
        sin(colatrad) * cos(lonrad),
        sin(colatrad) * sin(lonrad),
        cos(colatrad)
    ])
Exemple #55
0
def plot_den_win_diff():
    apex = Apex(date=2003)
    qlat, qlon = apex.convert(-90, 0, source='apex', dest='geo', height=400)

    plt.close('all')
    #plt.figure(figsize=(7.26, 9.25))
    plt.figure(figsize=(8.97, 3.45))
    alts = [130, 400]
    for ialt, alt in enumerate(alts):
        alt_ind = np.argmin(np.abs(g1a['Altitude'][0, 0, :]/1000-alt))
        alt_str = '%6.2f' % (g1a['Altitude'][0, 0, alt_ind]/1000)
        ax, projection = gcc.create_map(
                1, 2, ialt+1, 'polar', nlat=nlat, slat=slat, dlat=10,
                centrallon=g3ca.calculate_centrallon(g1a, 'polar',  useLT=True),
                coastlines=False)
        # density difference
        lon1, lat1, zdata1 = g3ca.contour_data('Rho', g1a, alt=alt)
        lon2, lat2, zdata2 = g3ca.contour_data('Rho', g2a, alt=alt)
        fp = (lat1[:,0]>slat) & (lat1[:,0]<nlat)
        lon0, lat0, zdata0 = lon1[fp, :], lat1[fp,:], \
                             (100*(zdata2-zdata1)/zdata1)[fp,:]
        hc = ax.contourf(lon0, lat0, zdata0, np.linspace(-20,20,21),
                         transform=ccrs.PlateCarree(), cmap='seismic',
                         extend='both')
        hc = plt.colorbar(hc, pad=0.17)
        hc.set_label(r'$100*\frac{\rho2-\rho1}{\rho1}$ (%)')
        # wind difference
        lon1, lat1, ewind1, nwind1 = g3ca.vector_data(g1a, 'neutral', alt=alt)
        lon2, lat2, ewind2, nwind2 = g3ca.vector_data(g2a, 'neutral', alt=alt)
        lon0, lat0 = lon1, lat1
        lon0, lat0, ewind0, nwind0 = g3ca.convert_vector(
                lon0, lat0, ewind2-ewind1, nwind2-nwind1, plot_type='polar',
                projection=projection)
        hq = ax.quiver(
                lon0, lat0, ewind0, nwind0, scale=500, scale_units='inches',
                regrid_shape=20,headwidth=5)
        ax.quiverkey(hq, 0.93, -0.1, 500, '500m/s')
        ax.scatter(qlon, qlat, color='k', transform=ccrs.PlateCarree())
        # rho difference
        # lon3, lat3, zdata3 = g3ca.contour_data('Rho', g1a, alt=alt)
        # lon4, lat4, zdata4 = g3ca.contour_data('Rho', g2a, alt=alt)
        # diffrho = 100*(zdata4-zdata3)/zdata3
        # hc = ax.contour(
        #         lon4, lat4, diffrho, [-10], transform=ccrs.PlateCarree(),
        #         colors='g',linestyles='-')

        plt.title('%s km' % alt_str, y=1.05)
    plt.text(0.5, 0.95, 'Time: '+titletime, fontsize=15,
            horizontalalignment='center', transform=plt.gcf().transFigure)
    plt.show()
    return
Exemple #56
0
def plot_den_win(show=True, save=True):
    apex = Apex(date=2003)
    qlat, qlon = apex.convert(-90, 0, source='apex', dest='geo', height=400)

    plt.close('all')
    plt.figure(figsize=(7.26, 9.25))
    g = g2a
    for ialt, alt in enumerate([130, 200, 300, 400, 500, 600]):
        alt_ind = np.argmin(np.abs(g['Altitude'][0, 0, 2:-2]/1000-alt))+2
        alt_str = '%6.2f' % (g['Altitude'][0, 0, alt_ind]/1000)
        ax, projection = gcc.create_map(
                3, 2, ialt+1, 'polar', nlat=nlat, slat=slat, dlat=10,
                centrallon=g3ca.calculate_centrallon(g, 'polar',  useLT=True),
                coastlines=False)
        # 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, 21,
                         transform=ccrs.PlateCarree(), cmap='jet',
                         extend='both')
        hc = plt.colorbar(hc, pad=0.17)
        hc.set_label(r'$\rho$ (kg/m$^3$)')

        # 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=1500, scale_units='inches',
                regrid_shape=20)
        ax.quiverkey(hq, 0.93, -0.1, 1000, '1000 m/s')
        ax.scatter(qlon, qlat, color='k', transform=ccrs.PlateCarree())

        # rho difference
        # lon3, lat3, zdata3 = g3ca.contour_data('Rho', g1a, alt=alt)
        # lon4, lat4, zdata4 = g3ca.contour_data('Rho', g2a, alt=alt)
        # diffrho = 100*(zdata4-zdata3)/zdata3
        # hc = ax.contour(
        #         lon4, lat4, diffrho, [-10], transform=ccrs.PlateCarree(),
        #         colors='g',linestyles='-')
        plt.title('%s km' % alt_str, y=1.05)
    plt.text(0.5, 0.95, 'Time: '+tstring, fontsize=15,
            horizontalalignment='center', transform=plt.gcf().transFigure)
    if show:
        plt.show()
    if save:
        plt.savefig(spath+'01_den_win_run2_%s%s.pdf' %(tstrday,tstring))
    return
Exemple #57
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
Exemple #58
0
def test__basevec_array():
    A = Apex(date=2000, refh=300)
    f1s, f2s = A._basevec([[0, 30], [60, 90]], 15, [[100, 200], [300, 400]])
    f11, f21 = fa.apxg2q(0, 15, 100, 1)[2:4]
    f12, f22 = fa.apxg2q(30, 15, 200, 1)[2:4]
    f13, f23 = fa.apxg2q(60, 15, 300, 1)[2:4]
    f14, f24 = fa.apxg2q(90, 15, 400, 1)[2:4]
    assert_allclose(f1s[0, 0], f11)
    assert_allclose(f1s[0, 1], f12)
    assert_allclose(f1s[1, 0], f13)
    assert_allclose(f1s[1, 1], f14)
    assert_allclose(f2s[0, 0], f21)
    assert_allclose(f2s[0, 1], f22)
    assert_allclose(f2s[1, 0], f23)
    assert_allclose(f2s[1, 1], f24)
Exemple #59
0
def test_basevectors_apex_scalar_geo():
    A = Apex(date=2000, refh=300)

    f1, f2, f3, g1, g2, g3, d1, d2, d3, e1, e2, e3 = A.basevectors_apex(60, 15, 100, coords='geo')

    _, _, _, _, f1_, f2_, _, d1_, d2_, d3_, _, e1_, e2_, e3_ = A._geo2apexall(60, 15, 100)

    assert_allclose(f1, f1_)
    assert_allclose(f2, f2_)
    assert_allclose(d1, d1_)
    assert_allclose(d2, d2_)
    assert_allclose(d3, d3_)
    assert_allclose(e1, e1_)
    assert_allclose(e2, e2_)
    assert_allclose(e3, e3_)