def plotMSBS(time=None, data=None, angles=(-125, 125), npts=30, mp=True, bs=True): """ Plot bow shock and magnetopause Sample compressed time: 2012-10-02T03:00:00 Sample "normal" time: 2012-07-22T12:00:00 """ import spacepy.omni as om import spacepy.empiricals as emp import spacepy.plot as splot import matplotlib.pyplot as plt if time is None and data is None: #use default time for "nominal" values time = spt.Ticktock('2012-10-02T03:00:00') omd = om.get_omni(time, dbase='OMNI2hourly') elif time is None and data is not None: omd = data elif time is not None and data is None: omd = om.get_omni(time, dbase='OMNI2hourly') else: raise ValueError('Use either "time" or "data" kwarg - not both.') fig, ax0 = plt.subplots(1) if mp: xmp, ymp = magnetopause(omd, np.linspace(angles[0], angles[1], npts)) ax0.plot(xmp, ymp, 'k:', label='Shue1997') if bs: x, y = get_BS_eq(omd, angles=angles, npts=npts) ax0.plot(x, y, 'k-.', label='Chao2002') ax0.set_aspect('equal') splot.dual_half_circle(ax=ax0) ax0.set_ylabel('Y$_{GSE}$ [R$_{E}$]') ax0.set_xlabel('X$_{GSE}$ [R$_{E}$]') # ax0.legend() ax0.set_xlim([-40, 40]) ax0.set_ylim([-45, 45]) return fig, ax0
def TsyParmod(self,date_t,imod): # Get SW data from omni omni_data = om.get_omni(date_t,dbase='qd5min') # Solar wind speed vxgse = omni_data['Vsw'] #vxgse = 400. vygse = 0. vzgse = 0. # Magnetic activity [SW pressure (nPa), Dst, ByIMF, BzIMF] parmod = np.zeros(10) parmod[0:4] = [omni_data['Pdyn'], omni_data['Dst'], omni_data['ByIMF'], omni_data['BzIMF']] if imod == 2: parmod[4:6]=omni_data['G'][0][0:2] elif imod == 3: parmod[4:10]=omni_data['W'] nsw = omni_data['Den_P'] #nsw = 5 return parmod,nsw,vxgse,vygse,vzgse
def getLmax(ticks, model='JKemp', dbase='QDhourly'): """ calculate a simple empirical model for Lmax - last closed drift-shell Uses the parametrized Lmax from: Koller and Morley (2010) 'Magnetopause shadowing effects for radiation belt models during high-speed solar wind streams' American Geophysical Union, Fall Meeting 2010, abstract #SM13A-1787 Parameters ========== ticks : spacepy.time.Ticktock Ticktock object of desired times model : string, optional 'JKemp' (default - empirical model of J. Koller) Returns ======= out : np.ndarray Lmax - L* of last closed drift shell Examples ======== >>> from spacepy.empiricals import getLmax >>> import spacepy.time as st >>> import datetime >>> ticks = st.tickrange(datetime.datetime(2000, 1, 1), datetime.datetime(2000, 1, 3), deltadays=1) array([ 7.4928412, 8.3585632, 8.6463423]) See Also ======== spacepy.LANLstar.LANLmax """ omni = om.get_omni(ticks, dbase=dbase) Dst = omni['Dst'] Lmax = np.zeros(len(Dst)) if model is 'JKemp': for i, iDst in enumerate(Dst): Lmax[i] = 6.07e-5 * iDst * iDst + 0.0436 * iDst + 9.37 else: raise ValueError('Invalid model selection') return Lmax
def getLmax(ticks, model='JKemp', dbase='QDhourly'): """ calculate a simple empirical model for Lmax - last closed drift-shell Uses the parametrized Lmax from: Koller and Morley (2010) 'Magnetopause shadowing effects for radiation belt models during high-speed solar wind streams' American Geophysical Union, Fall Meeting 2010, abstract #SM13A-1787 Parameters ========== ticks : spacepy.time.Ticktock Ticktock object of desired times model : string, optional 'JKemp' (default - empirical model of J. Koller) Returns ======= out : np.ndarray Lmax - L* of last closed drift shell Examples ======== >>> from spacepy.empiricals import getLmax >>> import spacepy.time as st >>> import datetime >>> ticks = st.tickrange(datetime.datetime(2000, 1, 1), datetime.datetime(2000, 1, 3), deltadays=1) array([ 7.4928412, 8.3585632, 8.6463423]) See Also ======== spacepy.LANLstar.LANLmax """ omni = om.get_omni(ticks, dbase=dbase) Dst = omni['Dst'] Lmax = np.zeros(len(Dst)) if model is 'JKemp': for i, iDst in enumerate(Dst): Lmax[i] = 6.07e-5*iDst*iDst + 0.0436*iDst + 9.37 else: raise ValueError('Invalid model selection') return Lmax
def setUp(self): self.ticks = spacepy.time.Ticktock(['2001-02-02T12:00:00', '2001-02-02T12:10:00'], 'ISO') self.actual = om.get_omni(self.ticks, dbase='Test') self.expected = {'ByIMF': array([ 0.2 , -0.04999999]), 'Bz1': array([-0.1 , 0.13333333]), 'Bz2': array([-0.1 , 0.13333333]), 'Bz3': array([-0.1 , 0.13333333]), 'Bz4': array([-0.1 , 0.13333333]), 'Bz5': array([-0.1 , 0.13333333]), 'Bz6': array([-0.1 , 0.13333333]), 'BzIMF': array([-0.1 , 0.13333333]), 'DOY': array([ 33., 33.]), 'Dst': array([-9., -9.]), 'G': array([[ 0.01 , 0.03 , 0.01 ], [ 0.01 , 0.025 , 0.00833333]]), 'Hr': array([ 12. , 12.16666667]), 'Kp': array([ 0.30000001, 0.30000001]), 'Pdyn': array([ 1.07000005, 1.05500005]), 'Qbits': {'ByIMF': array([ 1., 1., 1., 2.]), 'BzIMF': array([ 0., 2., 2., 2.]), 'G': array([[ 2., 2., 2.], [ 2., 2., 2.], [ 2., 2., 2.], [ 2., 2., 2.]]), 'Pdyn': array([ 0., 1., 0., 0.]), 'W': array([[ 1., 0., 0., 2., 2., 2.], [ 2., 0., 0., 2., 2., 2.], [ 1., 0., 0., 2., 2., 2.], [ 1., 0., 0., 2., 2., 2.]]), 'dens': array([ 1., 1., 1., 1.]), 'velo': array([ 2., 2., 2., 2.])}, 'RDT': array([ 730518.5 , 730518.50694444]), 'UTC': array([datetime.datetime(2001, 2, 2, 12, 0), datetime.datetime(2001, 2, 2, 12, 10)]), 'W': array([[ 0.026 , 0.017 , 0.31600001, 0.006 , 0.017 , 0.022 ], [ 0.02466667, 0.01566667, 0.31433334, 0.0055 , 0.015 , 0.01983333]]), 'Year': array([2001, 2001]), 'akp3': array([ 1.02999997, 0.99499997]), 'dens': array([ 3.20000005, 3.15000006]), 'velo': array([ 396., 396.])}
def add_omni(self, keylist=None): """ add omni data to instance according to the tickrange in ticks """ import spacepy.omni as om assert 'ticks' in self.__dict__ , \ "Provide tick range with 'setup_ticks'" omni = om.get_omni(self.ticks) if 'params' not in self.__dict__: self.params = {} if keylist is None: # add all keys self.params = omni else: # just add requested keys for key in keylist: self.params[key] = omni[key]
def setUp(self): super(empFunctionTests, self).setUp() self.ticks = spt.tickrange('2001-01-01T12:00:00','2001-01-04T00:00:00',.25) self.omnivals = om.get_omni(self.ticks, dbase='Test')
def getPlasmaPause(ticks, model='M2002', LT='all', omnivals=None): """ Plasmapause location model(s) CA1992 -- Carpenter, D. L., and R. R. Anderson, An ISEE/whistler model of equatorial electron density in the magnetosphere, J. Geophys. Res., 97, 1097, 1992. M2002 -- Moldwin, M. B., L. Downward, H. K. Rassoul, R. Amin, and R. R. Anderson, A new model of the location of the plasmapause: CRRES results, J. Geophys. Res., 107(A11), 1339, doi:10.1029/2001JA009211, 2002. RT1970 -- Rycroft, M. J., and J. O. Thomas, The magnetospheric plasmapause and the electron density trough at the alouette i orbit, Planetary and Space Science, 18(1), 65-80, 1970 Parameters ========== ticks : spacepy.time.Ticktock TickTock object of desired times Lpp_model : string, optional 'CA1992' or 'M2002' (default) CA1992 returns the Carpenter and Anderson model, M2002 returns the Moldwin et al. model LT : int, float requested local time sector, 'all' is valid option omnivals : spacepy.datamodel.SpaceData, dict dict-like containing UTC (datetimes) and Kp keys Returns ======= out : float Plasmapause radius in Earth radii Examples ======== >>> import spacepy.time as spt >>> import spacepy.empiricals as emp >>> ticks = spt.tickrange('2002-01-01T12:00:00','2002-01-04T00:00:00',.25) >>> emp.getPlasmaPause(ticks) array([ 6.42140002, 6.42140002, 6.42140002, 6.42140002, 6.42140002, 6.42140002, 6.42140002, 6.26859998, 5.772 , 5.6574 , 5.6574 ]) """ def calcLpp(Kpmax, A, B, power=1): currLpp = A - B*Kpmax**power return currLpp model_list = ['CA1992', 'M2002', 'RT1970'] if model == 'CA1992': if LT!='all': print('No LT dependence currently supported for this model') if model not in model_list: raise ValueError("Please specify a valid model:\n{0}".format(' or '.join(model_list))) if LT=='all': parA = {'CA1992': 5.6, 'M2002': 5.39, 'RT1970': 5.64} parB = {'CA1992': 0.46, 'M2002': 0.382, 'RT1970': 0.78} priorvals = {'CA1992': datetime.timedelta(hours=24), 'M2002': datetime.timedelta(hours=12), 'RT1970': datetime.timedelta(0)} A, B = parA[model], parB[model] prior = priorvals[model] else: try: float(LT) except (ValueError, TypeError): raise ValueError("Please specify a valid LT:\n'all' or a numeric type") parA = {'CA1992': [5.6]*24, 'M2002': [5.7]*3+[6.05]*6+[5.2]*6+[4.45]*6+[5.7]*3, 'RT1970': [5.64]*24} parB = {'CA1992': [0.46]*24, 'M2002': [0.42]*3+[0.573]*6+[0.425]*6+[0.167]*6+[0.42]*3, 'RT1970': [0.78]*24} priorvals = {'CA1992': [datetime.timedelta(hours=24)]*24, 'M2002': [datetime.timedelta(hours=12)]*24, 'RT1970': [datetime.timedelta(0)]*24} try: LThr = long(LT) except NameError: LThr = int(LT) prior = priorvals[model][LThr] A, B = parA[model][LThr], parB[model][LThr] st, en = ticks.UTC[0]-prior, ticks.UTC[-1] if omnivals is None: omdat = om.get_omni(spt.tickrange(st, en, 1.0/24.0), dbase='QDhourly') else: #now test for sanity of input try: assert isinstance(omnivals, dict) except: raise TypeError('Not a valid input type for omnivals, expected spacepy.datamodel.SpaceData') try: assert 'UTC' in omnivals assert 'Kp' in omnivals except: raise KeyError('Required data not found in input dict-like (omnivals)') omdat = omnivals einds, oinds = tb.tOverlap([st, en], omdat['UTC']) utc = np.array(omdat['UTC'])[oinds] Kp = np.array(omdat['Kp'])[oinds] Lpp = np.zeros(len(ticks)) if model == 'RT1970': power = 0.5 else: power = 1 for i, t1 in enumerate(ticks.UTC): t0 = t1-prior iprevday, dum = tb.tOverlap(utc, [t0, t1]) if iprevday: Kpmax = max(Kp[iprevday]) Lpp[i] = calcLpp(Kpmax, A, B, power=power) else: Lpp[i] = np.nan return Lpp
def get_omni(time_series, dbase='QDhourly'): return om.get_omni(time_series, dbase=dbase)
################### # Import databases ################### ### CRRES database : cdf (flux etc data). At unit level, possible to have 500ms precision (but binary files) os.chdir("/home/anissa/Bureau/Stage/Code CWI/Data/") cdf = pycdf.CDF('crres_h0_mea_19901006_v01.cdf') # CRRES Database Epoch=cdf['Epoch'][:] # vector of time of the CRRES Database print Epoch ticks = tim.Ticktock(Epoch, 'UTC') #print(cdf) ### OMNI database : data_omni (Kp, Dst etc data) for the same dates # spacepy.toolbox.update(all=True) data_omni=omni.get_omni(Epoch) #data_omni.tree(levels=1) ### CRRES Orbit Survey database (start time of CRRES orbit number data) orbit_survey=pd.read_csv('crres_orbit_survey_wFormat.csv') # Use orbit_survey (in csv file), dates of this file, and Epoch in cdf - CAREFUL : delete the line of the 183. orbit, date problem ! ### import factor for determining outer boundary condition factor_boundaries=pd.read_csv('LANL_satellite.csv') # 4 energy channels are considered : Col1 for mu=100, Col2 for mu=200 - 316, Col3 ofr mu=501, Col5 for mu=794 - 1000 boundary_factor=pd.Series(factor_boundaries['Col1'], index=factor_boundaries['DOY']) ################### # Build Database with Pandas ################### ### With CRRES database, extract position and time of the satellite (root of the database) # define coordonates of the satellite
def getDststar(ticks, model='OBrien', dbase='QDhourly'): """Calculate the pressure-corrected Dst index, Dst* We need to add in the references to the models here! Parameters ========== ticks : spacepy.time.Ticktock TickTock object of desired times (will be interpolated from hourly OMNI data) OR dictionary including 'Pdyn' and 'Dst' keys where data are lists or arrays and Dst is in [nT], and Pdyn is in [nPa] Returns ======= out : float Dst* - the pressure corrected Dst index from OMNI [nT] Examples ======== Coefficients are applied to the standard formulation e.g. Burton et al., 1975 of Dst* = Dst - b*sqrt(Pdyn) + c The default is the O'Brien and McPherron model (2002). Other options are Burton et al. (1975) and Borovsky and Denton (2010) >>> import spacepy.time as spt >>> import spacepy.omni as om >>> import spacepy.empiricals as emp >>> ticks = spt.tickrange('2000-10-16T00:00:00', '2000-10-31T12:00:00', 1/24.) >>> dststar = emp.getDststar(ticks) >>> dststar[0] -21.317220132108943 User-determined coefficients can also be supplied as a two-element list or tuple of the form (b,c), e.g. >>> dststar = emp.getDststar(ticks, model=(2,11)) #b is extreme driving from O'Brien We have chosen the OBrien model as the default here as this was rigorously determined from a very long data set and is pertinent to most conditions. It is, however, the most conservative correction. Additionally, Siscoe, McPherron and Jordanova (2005) argue that the pressure contribution to Dst diminishes during magnetic storms. To show the relative differences, run the following example: >>> import matplotlib.pyplot as plt >>> params = [('Burton','k-'), ('OBrien','r-'), ('Borovsky','b-')] >>> for model, col in params: dststar = getDststar(ticks, model=model) plt.plot(ticks.UTC, dststar, col) """ model_params = { 'Burton': (15.8, 20), 'OBrien': (7.26, 11), 'Borovsky': (20.7, 27.7) } if isinstance(model, str): try: b, c = model_params[model] except KeyError: raise ValueError('Invalid pressure correction model selected') else: try: b, c = model[0], model[1] except (KeyError, IndexError): raise ValueError('Invalid coefficients set: must be of form (b,c)') if isinstance(ticks, spt.Ticktock): omni = om.get_omni(ticks, dbase=dbase) P, Dst = omni['Pdyn'], omni['Dst'] elif isinstance(ticks, dict): P, Dst = ticks['Pdyn'], ticks['Dst'] if isinstance(P, list): P, Dst = np.array(P), np.array(Dst) #get Dst* Dststar = Dst - b * P**0.5 + c return Dststar
def getPlasmaPause(ticks, model='M2002', LT='all', omnivals=None): """ Plasmapause location model(s) CA1992 -- Carpenter, D. L., and R. R. Anderson, An ISEE/whistler model of equatorial electron density in the magnetosphere, J. Geophys. Res., 97, 1097, 1992. M2002 -- Moldwin, M. B., L. Downward, H. K. Rassoul, R. Amin, and R. R. Anderson, A new model of the location of the plasmapause: CRRES results, J. Geophys. Res., 107(A11), 1339, doi:10.1029/2001JA009211, 2002. RT1970 -- Rycroft, M. J., and J. O. Thomas, The magnetospheric plasmapause and the electron density trough at the alouette i orbit, Planetary and Space Science, 18(1), 65-80, 1970 Parameters ========== ticks : spacepy.time.Ticktock TickTock object of desired times Lpp_model : string, optional 'CA1992' or 'M2002' (default) CA1992 returns the Carpenter and Anderson model, M2002 returns the Moldwin et al. model LT : int, float requested local time sector, 'all' is valid option omnivals : spacepy.datamodel.SpaceData, dict dict-like containing UTC (datetimes) and Kp keys Returns ======= out : float Plasmapause radius in Earth radii Examples ======== >>> import spacepy.time as spt >>> import spacepy.empiricals as emp >>> ticks = spt.tickrange('2002-01-01T12:00:00','2002-01-04T00:00:00',.25) >>> emp.getPlasmaPause(ticks) array([ 6.42140002, 6.42140002, 6.42140002, 6.42140002, 6.42140002, 6.42140002, 6.42140002, 6.26859998, 5.772 , 5.6574 , 5.6574 ]) """ def calcLpp(Kpmax, A, B, power=1): currLpp = A - B * Kpmax**power return currLpp model_list = ['CA1992', 'M2002', 'RT1970'] if model == 'CA1992': if LT != 'all': print('No LT dependence currently supported for this model') if model not in model_list: raise ValueError("Please specify a valid model:\n{0}".format( ' or '.join(model_list))) if LT == 'all': parA = {'CA1992': 5.6, 'M2002': 5.39, 'RT1970': 5.64} parB = {'CA1992': 0.46, 'M2002': 0.382, 'RT1970': 0.78} priorvals = { 'CA1992': datetime.timedelta(hours=24), 'M2002': datetime.timedelta(hours=12), 'RT1970': datetime.timedelta(0) } A, B = parA[model], parB[model] prior = priorvals[model] else: try: float(LT) except (ValueError, TypeError): raise ValueError( "Please specify a valid LT:\n'all' or a numeric type") parA = { 'CA1992': [5.6] * 24, 'M2002': [5.7] * 3 + [6.05] * 6 + [5.2] * 6 + [4.45] * 6 + [5.7] * 3, 'RT1970': [5.64] * 24 } parB = { 'CA1992': [0.46] * 24, 'M2002': [0.42] * 3 + [0.573] * 6 + [0.425] * 6 + [0.167] * 6 + [0.42] * 3, 'RT1970': [0.78] * 24 } priorvals = { 'CA1992': [datetime.timedelta(hours=24)] * 24, 'M2002': [datetime.timedelta(hours=12)] * 24, 'RT1970': [datetime.timedelta(0)] * 24 } try: LThr = long(LT) except NameError: LThr = int(LT) prior = priorvals[model][LThr] A, B = parA[model][LThr], parB[model][LThr] st, en = ticks.UTC[0] - prior, ticks.UTC[-1] if omnivals is None: omdat = om.get_omni(spt.tickrange(st, en, 1.0 / 24.0), dbase='QDhourly') else: #now test for sanity of input try: assert isinstance(omnivals, dict) except: raise TypeError( 'Not a valid input type for omnivals, expected spacepy.datamodel.SpaceData' ) try: assert 'UTC' in omnivals assert 'Kp' in omnivals except: raise KeyError( 'Required data not found in input dict-like (omnivals)') omdat = omnivals einds, oinds = tb.tOverlap([st, en], omdat['UTC']) utc = np.array(omdat['UTC'])[oinds] Kp = np.array(omdat['Kp'])[oinds] Lpp = np.zeros(len(ticks)) if model == 'RT1970': power = 0.5 else: power = 1 for i, t1 in enumerate(ticks.UTC): t0 = t1 - prior iprevday, dum = tb.tOverlap(utc, [t0, t1]) if iprevday: Kpmax = max(Kp[iprevday]) Lpp[i] = calcLpp(Kpmax, A, B, power=power) else: Lpp[i] = np.nan return Lpp
def getMPstandoff(ticks, dbase='QDhourly', alpha=[]): """Calculates the Shue et al. (1997) subsolar magnetopause radius Shue et al. (1997), A new functional form to study the solar wind control of the magnetopause size and shape, J. Geophys. Res., 102(A5), 9497–9511, doi:10.1029/97JA00196. Parameters ========== ticks : spacepy.time.Ticktock TickTock object of desired times (will be interpolated from hourly OMNI data) OR dictionary of form {'P': [], 'Bz': []} Where P is SW ram pressure [nPa] and Bz is IMF Bz (GSM) [nT] alpha : list Used as an optional return value to obtain the flaring angles. To use, assign an empty list and pass to this function through the keyword argument. The list will be modified in place, adding the flaring angles for each time step. Returns ======= out : float Magnetopause (sub-solar point) standoff distance [Re] Examples ======== >>> import spacepy.time as spt >>> import spacepy.empiricals as emp >>> ticks = spt.tickrange('2002-01-01T12:00:00','2002-01-04T00:00:00',.25) >>> emp.getMPstandoff(ticks) array([ 10.57319537, 10.91327764, 10.75086873, 10.77577207, 9.78180261, 11.0374474 , 11.4065 , 11.27555451, 11.47988573, 11.8202582 , 11.23834814]) >>> data = {'P': [2,4], 'Bz': [-2.4, -2.4]} >>> emp.getMPstandoff(data) array([ 9.96096838, 8.96790412]) """ if type(ticks) == spt.Ticktock: omni = om.get_omni(ticks, dbase=dbase) P, Bz = omni['Pdyn'], omni['BzIMF'] elif isinstance(ticks, dict): P, Bz = ticks['P'], ticks['Bz'] try: len(P) except TypeError: P = [P] try: len(Bz) except TypeError: Bz = [Bz] else: raise (TypeError('Invalid Input type')) try: # Initialize r0 and make P and Bz numpy arrays r0 = np.zeros((len(P)), dtype=float) Bz = np.array(Bz) P = np.array(P) # Find where Bz >= 0 and where it is < 0 iBzPos = np.where(Bz >= 0) iBzNeg = np.where(Bz < 0) # Calculate r0 r0[iBzPos] = (11.4 + 0.013 * Bz[iBzPos]) * P[iBzPos]**(-1 / 6.6) r0[iBzNeg] = (11.4 + 0.140 * Bz[iBzNeg]) * P[iBzNeg]**(-1 / 6.6) flarang = (0.58 - 0.01 * Bz) * (1.0 + 0.01 * P) alpha.extend(flarang) return r0 except TypeError: raise TypeError("Please check for valid input types")
def getMPstandoff(ticks, dbase='QDhourly', alpha=[]): """Calculates the Shue et al. (1997) subsolar magnetopause radius Shue et al. (1997), A new functional form to study the solar wind control of the magnetopause size and shape, J. Geophys. Res., 102(A5), 9497–9511, doi:10.1029/97JA00196. Parameters ========== ticks : spacepy.time.Ticktock TickTock object of desired times (will be interpolated from hourly OMNI data) OR dictionary of form {'P': [], 'Bz': []} Where P is SW ram pressure [nPa] and Bz is IMF Bz (GSM) [nT] alpha : list Used as an optional return value to obtain the flaring angles. To use, assign an empty list and pass to this function through the keyword argument. The list will be modified in place, adding the flaring angles for each time step. Returns ======= out : float Magnetopause (sub-solar point) standoff distance [Re] Examples ======== >>> import spacepy.time as spt >>> import spacepy.empiricals as emp >>> ticks = spt.tickrange('2002-01-01T12:00:00','2002-01-04T00:00:00',.25) >>> emp.getMPstandoff(ticks) array([ 10.57319537, 10.91327764, 10.75086873, 10.77577207, 9.78180261, 11.0374474 , 11.4065 , 11.27555451, 11.47988573, 11.8202582 , 11.23834814]) >>> data = {'P': [2,4], 'Bz': [-2.4, -2.4]} >>> emp.getMPstandoff(data) array([ 9.96096838, 8.96790412]) """ if type(ticks) == spt.Ticktock: omni = om.get_omni(ticks, dbase=dbase) P, Bz = omni['Pdyn'], omni['BzIMF'] elif isinstance(ticks, dict): P, Bz = ticks['P'], ticks['Bz'] try: len(P) except TypeError: P = [P] try: len(Bz) except TypeError: Bz = [Bz] else: raise(TypeError('Invalid Input type')) try: # Initialize r0 and make P and Bz numpy arrays r0 = np.zeros((len(P)), dtype=float) Bz = np.array(Bz) P = np.array(P) # Find where Bz >= 0 and where it is < 0 iBzPos = np.where(Bz >= 0) iBzNeg = np.where(Bz < 0) # Calculate r0 r0[iBzPos] = (11.4 + 0.013*Bz[iBzPos])*P[iBzPos]**(-1/6.6) r0[iBzNeg] = (11.4 + 0.140*Bz[iBzNeg])*P[iBzNeg]**(-1/6.6) flarang = (0.58 - 0.01*Bz)*(1.0 + 0.01*P) alpha.extend(flarang) return r0 except TypeError: raise TypeError("Please check for valid input types")
def getMPstandoff(ticks, dbase='QDhourly'): """Calculates the Shue et al. (1997) subsolar magnetopause radius Lets put the full reference here Parameters ========== ticks : spacepy.time.Ticktock TickTock object of desired times (will be interpolated from hourly OMNI data) OR dictionary of form {'P': [], 'Bz': []} Where P is SW ram pressure [nPa] and Bz is IMF Bz (GSM) [nT] Returns ======= out : float Magnetopause (sub-solar point) standoff distance [Re] Examples ======== >>> import spacepy.time as spt >>> import spacepy.empiricals as emp >>> ticks = spt.tickrange('2002-01-01T12:00:00','2002-01-04T00:00:00',.25) >>> emp.ShueMP(ticks) array([ 10.57319537, 10.91327764, 10.75086873, 10.77577207, 9.78180261, 11.0374474 , 11.4065 , 11.27555451, 11.47988573, 11.8202582 , 11.23834814]) >>> data = {'P': [2,4], 'Bz': [-2.4, -2.4]} >>> emp.ShueMP(data) array([ 9.96096838, 8.96790412]) """ if type(ticks) == spt.Ticktock: omni = om.get_omni(ticks, dbase=dbase) P, Bz = omni['Pdyn'], omni['BzIMF'] elif isinstance(ticks, dict): P, Bz = ticks['P'], ticks['Bz'] try: len(P) except TypeError: P = [P] try: len(Bz) except TypeError: Bz = [Bz] else: raise(TypeError('Invalid Input type')) try: # Initialize r0 and make P and Bz numpy arrays r0 = np.zeros((len(P)), dtype=float) Bz = np.array(Bz) P = np.array(P) # Find where Bz >= 0 and where it is < 0 iBzPos = np.where(Bz >= 0) iBzNeg = np.where(Bz < 0) # Calculate r0 r0[iBzPos] = (11.4 + 0.013*Bz[iBzPos])*P[iBzPos]**(-1/6.6) r0[iBzNeg] = (11.4 + 0.140*Bz[iBzNeg])*P[iBzNeg]**(-1/6.6) return r0 except TypeError: raise TypeError("Please check for valid input types")
# import spacepy.irbempy as ib # t = spt.Ticktock(['2002-02-02T12:00:00', '2002-02-02T12:10:00'], 'ISO') # y = spc.Coords([[3,0,0],[2,0,0]], 'GEO', 'car') # result=ib.get_Bfield(t,y) # print result # endregion # region Description Fetch and Plot OMNI Data import spacepy.omni as om import spacepy.time as spt import matplotlib.pyplot as plt ticks = spt.tickrange('2007-03-07T00:00:00', \ '2007-05-16T00:00:00', 1./24.) data = om.get_omni(ticks) plt.Figure() ax0 = plt.subplot(211) plt.plot(data['UTC'], data['Dst'], 'r-') ax1 = plt.subplot(212) plt.plot(data['UTC'],data['velo'], 'k-') ax0.set_ylabel('D$_{st}$ [nT]') ax1.set_ylabel('V$_{sw}$ [km s$^{1}$]') ax1.set_xlabel('UTC') plt.show() # endregion
def getDststar(ticks, model='OBrien', dbase='QDhourly'): """Calculate the pressure-corrected Dst index, Dst* We need to add in the references to the models here! Parameters ========== ticks : spacepy.time.Ticktock TickTock object of desired times (will be interpolated from hourly OMNI data) OR dictionary including 'Pdyn' and 'Dst' keys where data are lists or arrays and Dst is in [nT], and Pdyn is in [nPa] Returns ======= out : float Dst* - the pressure corrected Dst index from OMNI [nT] Examples ======== Coefficients are applied to the standard formulation e.g. Burton et al., 1975 of Dst* = Dst - b*sqrt(Pdyn) + c The default is the O'Brien and McPherron model (2002). Other options are Burton et al. (1975) and Borovsky and Denton (2010) >>> import spacepy.time as spt >>> import spacepy.omni as om >>> import spacepy.empiricals as emp >>> ticks = spt.tickrange('2000-10-16T00:00:00', '2000-10-31T12:00:00', 1/24.) >>> dststar = emp.getDststar(ticks) >>> dststar[0] -21.317220132108943 User-determined coefficients can also be supplied as a two-element list or tuple of the form (b,c), e.g. >>> dststar = emp.getDststar(ticks, model=(2,11)) #b is extreme driving from O'Brien We have chosen the OBrien model as the default here as this was rigorously determined from a very long data set and is pertinent to most conditions. It is, however, the most conservative correction. Additionally, Siscoe, McPherron and Jordanova (2005) argue that the pressure contribution to Dst diminishes during magnetic storms. To show the relative differences, run the following example: >>> import matplotlib.pyplot as plt >>> params = [('Burton','k-'), ('OBrien','r-'), ('Borovsky','b-')] >>> for model, col in params: dststar = getDststar(ticks, model=model) plt.plot(ticks.UTC, dststar, col) """ model_params = {'Burton': (15.8, 20), 'OBrien': (7.26, 11), 'Borovsky': (20.7,27.7)} if isinstance(model, str): try: b, c = model_params[model] except KeyError: raise ValueError('Invalid pressure correction model selected') else: try: b, c = model[0], model[1] except (KeyError, IndexError): raise ValueError('Invalid coefficients set: must be of form (b,c)') if isinstance(ticks, spt.Ticktock): omni = om.get_omni(ticks, dbase=dbase) P, Dst = omni['Pdyn'], omni['Dst'] elif isinstance(ticks, dict): P, Dst = ticks['Pdyn'], ticks['Dst'] if isinstance(P, list): P, Dst = np.array(P), np.array(Dst) #get Dst* Dststar = Dst - b*P**0.5 + c return Dststar